Typescript接口泛型:仅当T的联合类型为'A |时,才允许泛型T。 B'

时间:2020-04-26 11:21:19

标签: typescript generics

export type Message = [
    {
        id: 'message',
        settings: ComponentSettings;
    }
];

type Industrial = [
    {
        id: 'title',
        settings: ComponentSettings;
    },
    {
        id: 'text',
        settings: ComponentSettings;
    }
];

仅当T为'Message |时,我才允许T工业”

export interface CardRef<T> {
    id: 'Industrial' | 'Message';
    childInstances?: T;
}

1 个答案:

答案 0 :(得分:2)

听起来您可能希望CardRef是联合类型,而不是带有通用参数的类型:

export type CardRef =
    {
        id: 'Industrial';
        childInstances?: Industrial;
    }
    |
    {
        id: 'Message';
        childInstances?: Message;
    };

用法:

let x: CardRef = { id: 'Industrial' };
x.childInstances; // type is Industrial | undefined

let y: CardRef = { id: 'Message' };
y.childInstances; // type is Message | undefined

On the playground

相关问题