Home > Enterprise >  generics use default value in typescript
generics use default value in typescript

Time:03-30

export type DefaultResponse = Record<string, any>
export type SuccessCallbackResult<T extends DefaultResponse = DefaultResponse> = {
    State: Number;
    Body: T,
    Msg: string,
};

or

export type SuccessCallbackResult<T={}> = {
    State: Number;
    Body: T,
    Msg: string,
};

Both of these modes of use can be run,I don't know which way is better? First kind Is it standard to use it this way?

What would you think would be the best way write this?

CodePudding user response:

If you use the second example, T can be everything. {} basically means any - null (every non nullish value).

You should use the first example because it's pretty likely for an API to return an object, so if you don't know the exact properties, you still know it's an object.

It also works without an extra type:

export type SuccessCallbackResult<T extends object = Record<string, any>> = {
    State: Number;
    Body: T,
    Msg: string,
};
  • Related