泛型在打字稿中使用默认值
generics use default value in typescript
export type DefaultResponse = Record<string, any>
export type SuccessCallbackResult<T extends DefaultResponse = DefaultResponse> = {
State: Number;
Body: T,
Msg: string,
};
或
export type SuccessCallbackResult<T={}> = {
State: Number;
Body: T,
Msg: string,
};
这两种使用方式都可以运行,不知道哪种方式更好?
第一种这样使用是否标准?
您认为最好的写法是什么?
如果你使用第二个例子,T
可以是一切。 {}
基本上意味着 any - null
(每个非空值)。
您应该使用第一个示例,因为它很可能是 API 到 return 一个对象,所以如果您不知道确切的属性,您仍然知道它是一个对象。
它也可以在没有额外类型的情况下工作:
export type SuccessCallbackResult<T extends object = Record<string, any>> = {
State: Number;
Body: T,
Msg: string,
};
export type DefaultResponse = Record<string, any>
export type SuccessCallbackResult<T extends DefaultResponse = DefaultResponse> = {
State: Number;
Body: T,
Msg: string,
};
或
export type SuccessCallbackResult<T={}> = {
State: Number;
Body: T,
Msg: string,
};
这两种使用方式都可以运行,不知道哪种方式更好? 第一种这样使用是否标准?
您认为最好的写法是什么?
如果你使用第二个例子,T
可以是一切。 {}
基本上意味着 any - null
(每个非空值)。
您应该使用第一个示例,因为它很可能是 API 到 return 一个对象,所以如果您不知道确切的属性,您仍然知道它是一个对象。
它也可以在没有额外类型的情况下工作:
export type SuccessCallbackResult<T extends object = Record<string, any>> = {
State: Number;
Body: T,
Msg: string,
};