简体   繁体   中英

Unable to assign a default value using Generics in Typescript

I have this piece of code in 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 . Generic type T extends EmptyOutputBody and I thought that assigning an object of Parent class ( EmptyOutputBody ) of Generic type T would work for me. But this code gives me error on output property. it says

Type 'EmptyOutputBody' is not assignable to type 'T'. 'EmptyOutputBody' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint '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 .

For the initial assignment, while declaring, you can use as syntax as below given example.

There is a huge discussion around that you can read more here.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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