如何让这个编译没有错误?我们使用的是 TypeScript 2.9.1。
interface IFoo {
type: 'foo';
foo: string;
}
interface IBar {
type: 'bar';
bar: string;
}
type FooBar = IFoo | IBar;
class Getter<T extends FooBar> {
private data: T;
constructor(data: T) {
this.data = data;
}
public getMe(): string {
const { data } = this;
// Property 'foo' does not exist on type 'T'.
// Property 'bar' does not exist on type 'T'.
return data.type === 'foo' ? data.foo : data.bar;
}
}
最佳答案
编译器不会缩小具有类型参数类型的变量。您可以显式键入变量,这将使代码进行编译:
public getMe(): string {
const data :FooBar = this.data;
return data.type === 'foo' ? data.foo : data.bar;
}
关于泛型中的 typescript 标记联合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50819907/