Issue
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?
Solution
isTextLink can be removed.
To keep this simpler, the interface will do :
interface Link {
label: string;
content: LinkReference | string ;
}
typeof content will give you the link type.
But if you really want separation for some reason, generics can help:
interface LinkBase<T> {
label: string;
// content can be string or LinkReference
// content is an example name, use whatever name you want
content: T ;
// other common attributes down here
}
export interface LinkWithLinkReference extends LinkBase<LinkReference> {
// other specific attributes down here
}
export interface LinkWithLinkText extends LinkBase<string> {
// other specific attributes down here
}
Answered By - exaucae
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.