【发布时间】:2021-06-19 01:30:07
【问题描述】:
假设我有对象使用_type_ 属性来编码运行时类型信息。
interface Foo {
_type_: '<foo>';
thing1: string;
}
interface Bar {
_type_: '<bar>'
thing2: number;
}
function helpme(input: Foo|Bar): string | number {
if (input._type_ === '<foo>') {
return input.thing1;
}
if (input._type_ === '<bar>') {
return input.thing2;
}
return 'N/A';
}
这一切都很好,而且效果很好。但是,我想将_type_ 签入抽象为一个函数,这样我的调用站点就不必都知道这个属性,他们可以直接调用该函数。
interface Foo {
_type_: '<foo>';
thing1: string;
}
interface Bar {
_type_: '<bar>'
thing2: number;
}
function typeIs(o: any, t: '<foo>' | '<bar>'): o is {_type_: t} {
return o && typeof(o) === 'object' && o._type_ === t;
}
function helpme(input: Foo|Bar): string | number {
if (typeIs(input, '<foo>')) {
return input.thing1;
}
if (typeIs(input, '<bar>')) {
return input.thing2;
}
return 'N/A';
}
问题是,这实际上不起作用;我收到一个错误:
't' refers to a value, but is being used as a type here. Did you mean 'typeof t'?
...这是有道理的。我要写的语法怎么写?
【问题讨论】:
标签: typescript