首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Typescript接口泛型:仅当T是联合类型'A | B‘时才允许泛型T

Typescript接口泛型:仅当T是联合类型'A | B‘时才允许泛型T
EN

Stack Overflow用户
提问于 2020-04-26 19:21:20
回答 1查看 32关注 0票数 0
代码语言:javascript
复制
export type Message = [
    {
        id: 'message',
        settings: ComponentSettings;
    }
];

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

我希望仅当T为'Message | Industrial‘时才允许T

代码语言:javascript
复制
export interface CardRef<T> {
    id: 'Industrial' | 'Message';
    childInstances?: T;
}
EN

回答 1

Stack Overflow用户

发布于 2020-04-26 19:36:50

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

代码语言:javascript
复制
export type CardRef =
    {
        id: 'Industrial';
        childInstances?: Industrial;
    }
    |
    {
        id: 'Message';
        childInstances?: Message;
    };

用法:

代码语言:javascript
复制
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

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61439824

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档