首页 > 解决方案 > Typescript:基于属性值的类型确定

问题描述

我很确定 Typescript 能够根据属性值确定扩展类,例如:

interface Base {
    type: string;
    child?: Base;
}

interface Ext extends Base {
    type: 'test';
    sth: string;
}

z({
    type: 'a',
    child: {
        type: 'b',
    }
}); // ok

z({
    type: 'a',
    child: {
        type: 'test',
        sth: 'val'
    }
}); // not ok

function z(input: Base) { }

上面的例子不起作用,TS 告诉我sthinterface 上不存在属性Base。由于属性上Ext的值,我需要更改什么以便 TS 将孩子理解为实际上是 type of ?'test'type

标签: typescript

解决方案


您需要将其声明为类型Ext并且它应该通过

let x: Ext = {
    type: 'test',
    sth: 'value'
}

推荐阅读