'Typescript: use either the one or other interface based on property value

I want to have a type that implements either the one or the other properties based on a given other property.

The type should have the following base structure:

interface LinkBase {
  label: string;
  isTextLink: boolean;
}

Depeinding on isTextLink it should have either linkReference or linkText as additional non-optional property:

// if isTextLink is false
export interface LinkWithLinkReference extends LinkBase {
  linkReference: LinkReference;
}

// if isTextLink is true
export interface LinkWithLinkText extends LinkBase {
   linkText: string;
}

I tried to create a union type where either the one or the other interface is allowed:

export type Link= LinkWithLinkReference | LinkWithLinkText;

but it does not take isTextLink value into account and in usage it gives me the following error:

"Property 'linkText' does not exist on type 'Link'.   Property 'linkText' does not exist on type 'LinkWithLinkReference'."

What would be the best way to create and use such type?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source