简体   繁体   English

打字稿覆盖通用属性

[英]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. 当我使用泛型调用createProp时,我希望它成为prop属性的新类型。 Currently, after running this method, the type is still - Base<any> . 当前,运行此方法后,类型仍为Base<any> There is a way to do it with TS? 有没有办法用TS做到这一点?

prop is defined as Base<any> - it'll never be a Base<T> , even if one is assigned to it. prop被定义为Base<any> -它永远不会是Base<T> ,即使为其分配了一个。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM