- 泛型
function demo<T>(arg: T): T {
return arg;
}
const t1 = demo<string>("hello");
console.log(t1);
const t2 = demo<number>(1);
console.log(t2);
let num = demo(10);
let str = demo("10");
function demo1<T>(arg: T[]): T[] {
console.log(arg.length);
return arg;
}
demo1([1, 2, 3]);
demo1(["a", "b"]);
interface ILength {
length: number;
}
function demo2<T extends ILength>(arg: T): T {
console.log(arg.length);
return arg;
}
demo2("hello");
demo2([1, 2, 3]);
demo2({ length: 100, name: "tom" });
function getProp<O, V extends keyof O>(obj: O, value: V) {
return obj[value];
}
console.log(getProp({ name: "tom", age: 20 }, "name"));
console.log(getProp({ name: "tom", age: 20 }, "age"));
console.log(getProp(18, "toFixed"));
console.log(getProp("abc", "split"));
console.log(getProp("abc", 1));
console.log(getProp(["a", "b"], "length"));
console.log(getProp(["a"], 1000));
interface IDemo<Type> {
demo: (value: Type) => Type;
demos: () => Type[];
}
let obj: IDemo<number> = {
demo(value) {
return value;
},
demos() {
return [1, 3, 5];
},
};
console.log(obj.demo(8));
console.log(obj.demos());
- 泛型类
class GenericNumber<NumType> {
defaultValue: NumType;
add: (x: NumType, y: NumType) => NumType;
}
const myNum = new GenericNumber();
myNum.defaultValue = 10;
- 泛型工具类
interface Props {
id: string;
children: number[];
}
type PartialProps = Partial<Props>;
let p1: Props = {
id: "",
children: [1],
};
let p2: PartialProps = {
children: [1, 3],
};
type ReadonlyProps = Readonly<Props>;
let p3: ReadonlyProps = {
id: "1",
children: [1, 3],
};
interface Props1 {
id: string;
title: string;
children: number[];
}
type PickProps = Pick<Props1, "id" | "title">;
let p4: PickProps = {
id: "123",
title: "test",
};
type RecordObj = Record<"a" | "b" | "c", string[]>;
let obj: RecordObj = {
a: ["a"],
b: ["b"],
c: ["c"],
};
- 索引签名类型
interface AnyObject {
[key: string]: number;
}
let obj: AnyObject = {
a: 1,
abc: 124,
abcde: 12345,
};
const arr = [1, 3, 5];
arr.forEach;
interface MyArray<Type> {
[index: number]: Type;
}
let arr1: MyArray<number> = [1, 3, 5];
arr1[0];
- 映射类型
type PropKeys = "x" | "y" | "z" | "a" | "b";
type Type1 = { x: number; y: number; z: number; a: number; b: number };
type Type2 = { [Key in PropKeys]: number };
type Props = { a: number; b: string; c: boolean };
type Type3 = { [key in keyof Props]: number };
type Props1 = { a: number; b: string; c: boolean };
type TypeA = Props1["a"];
type MyPartial<T> = {
[P in keyof T]?: T[P];
};
type PartialProps = MyPartial<Props>;
type TypeA1 = Props1["a" | "b"];
type TypeB1 = Props1[keyof Props];
let p: TypeB1 = false;