简单使用
// 泛型 ‘C’可随意取
function id<C>(value: C): C {
return value;
}
const num = id<number>(3);
let str = id<string>("3"); // <string>可省略
泛型约束
// 指定具体类型
function id1<C>(value: C[]): C[] {
console.log(c.length);
return value;
}
id1([1, 2, 3]);
// 添加约束
interface ILength {
length: number;
}
function id2<C extends ILength>(value: C): C {
console.log(c.length);
return value;
} // 表示传入的值必须具有length属性
id2("qwee");
id2([1, 2, 3]);
泛型多个类型变量
// keyof接受一个对象类型,生成以键名组成的联合类型,例:'name'|'age'
function getProp<Type, Key extends keyof Type>(obj: Type, key: Key) {
return obj[key];
}
getProp({ name: "jim" }, "name"); // 'jim'
getProp([1, 2, 3], 1); // 2
getProp("asdf", 2); // d
接口中使用泛型
interface IdFun<Type> {
id: (value: Type) => Type;
ids: () => Type[];
}
let IdObj: IdFun<number> = {
id(value) {
return value;
},
ids() {
return [123];
},
};
类中使用泛型
// 方法1
class Example1<Type> {
defaultValue: Type;
add: (x: Type, y: Type) => Type;
constructor(value: Type) {
this.defaultValue = value;
}
}
const numa = new Example1(19);
// 方法2
class Example2<Type> {
defaultValue: Type;
add: (x: Type, y: Type) => Type;
}
const myNum = new Example2<number>();
myNum.defaultValue = 123;
泛型工具类型
interface Props {
id: number;
children: number[];
}
// Partial<Type>,将类型Type的所有属性设置为可选
type PartialProps = Partial<Props>;
let pro: PartialProps = {}; // id、children此时为可选属性
// Readonly<Type>,将类型Type的所有属性设置只读
type ReadonlyProps = Readonly<Props>;
let pro1: ReadonlyProps = { id: 1, children: [1] };
// pro1.id=2 此时会报错
// Pick<Type>,从Type中选择属性来构造新类型
type PicckProps = Pick<Props, "id" | "children">;
// Record<Keys,Type>,Keys:表示对象有哪些属性;Type:表示属性类型
type RecordObj = Record<"a" | "b", string[]>;
let reObj: RecordObj = {
a: ["1"],
b: ["2"],
};
715

被折叠的 条评论
为什么被折叠?



