【发布时间】:2019-11-21 03:15:53
【问题描述】:
我正在尝试根据实例成员的类型缩小联合范围。如果我正在检查属性的返回类型,它似乎工作正常,但不适用于函数。
这是 TypeScript 中的限制/错误吗?还是我做错了什么?
谢谢!
enum Types {
A,
B
}
class A {
public get type(): Types.A { return Types.A; }
public getType(): Types.A { return Types.A; }
public getValue(): undefined { return undefined; }
}
class B {
public get type(): Types.B { return Types.B; }
public getType(): Types.B { return Types.B; }
public getValue(): string { return 'string'; }
}
type Classes = A | B;
const c = new A() as Classes;
if (c.getType() === Types.A) {
const v = c.getValue(); // typeof v: string | undefined (can't be inferred?)
}
if (c.getType() === Types.B) {
const v = c.getValue(); // typeof v: string | undefined (can't be inferred?)
}
if (c.type === Types.A) {
const v = c.getValue(); // typeof v: undefined (correct!)
}
if (c.type === Types.B) {
const v = c.getValue(); // typeof v: string (correct!)
}
【问题讨论】:
标签: typescript