Martin Ždila
Martin Ždila

Reputation: 3219

typescript tagged union in generic

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

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

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

Related Questions