简体   繁体   English

无法使用 Typescript 中的 Generics 分配默认值

[英]Unable to assign a default value using Generics in Typescript

I have this piece of code in Typescript.我在 Typescript 中有这段代码。

export class CommonResponse<T extends EmptyOutputBody> {
    output: T  = new EmptyOutputBody();
    successful: boolean = false;
    responseCode: number = 200;
}

export class EmptyOutputBody {
    alerts: string[] = [];
}

I wanted to assign a default value to the generic typed property output .我想为通用类型属性output分配一个默认值。 Generic type T extends EmptyOutputBody and I thought that assigning an object of Parent class ( EmptyOutputBody ) of Generic type T would work for me.通用类型T扩展EmptyOutputBody ,我认为分配通用类型T的父 class ( EmptyOutputBody )的 object 对我有用。 But this code gives me error on output property.但是这段代码在output属性上给了我错误。 it says它说

Type 'EmptyOutputBody' is not assignable to type 'T'.类型“EmptyOutputBody”不可分配给类型“T”。 'EmptyOutputBody' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'EmptyOutputBody' “EmptyOutputBody”可分配给“T”类型的约束,但“T”可以用约束“EmptyOutputBody”的不同子类型来实例化

Can someone help me how can I instantiate a generic type in this case, or how can I provide initial value to output which should be of type T or EmptyOutputBody .有人可以帮我在这种情况下如何实例化泛型类型,或者如何向output提供初始值,该值应该是TEmptyOutputBody类型。

For the initial assignment, while declaring, you can use as syntax as below given example.对于初始分配,在声明时,您可以使用 as 语法,如下所示。

There is a huge discussion around that you can read more here.有一个巨大的讨论,你可以在这里阅读更多。

https://github.com/microsoft/TypeScript/issues/36821 https://github.com/microsoft/TypeScript/issues/36821

export class CommonResponse<T extends EmptyOutputBody> {
  output: T = new EmptyOutputBody() as T; // Modify here
  successful: boolean = false;
  responseCode: number = 200;
}

export class EmptyOutputBody {
  alerts: string[] = [];
}
const res = new CommonResponse()
res.output = new EmptyOutputBody() // NO issue

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

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