Reputation: 3219
How to make this compile without errors? We are using 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;
}
}
Upvotes: 2
Views: 359
Reputation: 249716
The compiler will not narrow variables that have the type of type parameter. You can type the variable explicitly and that will get the code to compile:
public getMe(): string {
const data :FooBar = this.data;
return data.type === 'foo' ? data.foo : data.bar;
}
Upvotes: 2