如果不是为了炫技,大可不必使用泛型;但对于编写API、重构代码等场景,泛型确实能减少冗余代码,保持设计简洁,降低心智认知。
type generic#
type PartialUser = Partial<{ id: string; name: string;}>;
// Default 写法
type Response<Data extends object = { content: string }> = {
data: Data
isErr: boolean
}
type BlogResponse = Response<{ title: string, text: string }>
const res: Response = { content: "2233" };
types to functions
function fn <T, V, U>(params: ParamType): ReturnType {
return ...;
}
传递 arguments types to functions#
const objectKeys = <T extends object>(obj: T) => {
return Object.keys(obj) as Array<keyof T>;
}
generic interface#
interface Bar<T> {
<T> (args: T): T; // function
someProp: T; // normal key
}
generic classes#
class GenericNumber<NumType> {
zeroValue: NumType;
add: (x: NumType, y: NumType) => NumType;
}
let myGenericNumber = new GenericNumber<number>();
myGenericNumber.zeroValue = 0;
myGenericNumber.add = function (x, y) {
return x + y;
};