N Prafull
N Prafull

Reputation: 13

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.

Upvotes: 0

Views: 174

Answers (1)

xdeepakv
xdeepakv

Reputation: 8135

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

Upvotes: 0

Related Questions