如果不是为了炫技,大可不必使用泛型;
但对于编写API、重构代码等场景,泛型确实能减少冗余代码,保持设计简洁,降低心智认知。
Think of generic type aliases as type-level functions.
type generic#
type Identity<T> = T
type Nullable<T> = T | null
type Pair<T> = [T, T]
type Box<T> = { value: T }
type KeyValue<K, V> = { key: K; value: V }
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;
};