TypeScript 泛型中的标记联合
如何使这个编译没有错误?我们使用的是 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;
}
}
答案#1
编译器不会缩小具有类型参数类型的变量。你可以显式地指定变量的类型,这样代码就可以编译了:
public getMe(): string {
const data :FooBar = this.data;
return data.type === 'foo' ? data.foo : data.bar;
}
