【发布时间】:2020-02-16 17:31:41
【问题描述】:
我似乎无法弄清楚如何区分函数类型的可区分联合的成员。请参阅以下示例:
type _NumFunc = (n: number) => string;
type _StrFunc = (s: string) => string;
interface NumFunc extends _NumFunc { __type: 'NumFunc'; }
interface StrFunc extends _StrFunc { __type: 'StrFunc'; }
type Func = NumFunc | StrFunc;
let myNumFunc = ((n: number) => `Hello x${n}!`) as NumFunc;
let myStrFunc = ((s: string) => `Hello, ${s}!`) as StrFunc;
let funcGen = (n: number): Func => n % 2 == 0 ? myNumFunc : myStrFunc;
for (let i = 0; i < 2; i++)
{
let func = funcGen(i);
switch (func.__type)
{
case 'NumFunc':
console.log(func(3));
break;
case 'StrFunc':
console.log(func('World!'));
break;
default:
console.error(func);
console.error('How did this happen?');
break;
}
}
我希望这个程序的输出应该是:
你好 x3!
你好,世界!
但是如果您run this code,您会看到每次迭代都会调用默认情况。简单地记录func 将显示函数对象,但尝试访问对象上的__type 会引发错误,指出func 的类型是never。为什么这种方法不起作用,是否有任何方法允许使用函数类型的可区分联合?
【问题讨论】:
标签: typescript