undefined
undefined

Reputation: 6844

Typescript override generic property

I have the following code:

class Base<T> {}

class Test {
  prop: Base<any>;

  createProp<T>() {
    this.prop = new Base<T>();
  }
}

const test = new Test();

test.createProp<{ a: number }>();

test.prop // Base<any> expected Base<{ a: number }>

When I call createProp with the generic, I want it to be the new type of the prop property. Currently, after running this method, the type is still - Base<any>. There is a way to do it with TS?

Upvotes: 0

Views: 533

Answers (1)

MTCoster
MTCoster

Reputation: 6145

prop is defined as Base<any> - it’ll never be a Base<T>, even if one is assigned to it.

In order to achieve this behaviour, you’ll have to make your class generic instead of just the method:

class Base<T> {}

class Test<T> {
  prop: Base<T>;

  createProp() {
    this.prop = new Base<T>();
  }
}

const test = new Test<{ a: number }>();

test.createProp();

test.prop

Alternatively, if you’re really against using a generic class, you could use a type assertion:

class Base<T> {}

class Test {
  prop: Base<any>;

  createProp<T>() {
    this.prop = new Base<T>();
  }
}

const test = new Test();

test.createProp<{ a: number }>();

test.prop as Base<{ a: number }>
// --- or ---
<Base<{ a: number }>> test.prop

Upvotes: 1

Related Questions