补充-2
Tutorial: TS初级二
Category: TS
Published: 2026-04-07 13:58:26
Views: 20
Likes: 0
Comments: 0
- infer 关键字
export default {};
type ID = number[];
type IName = string[];
type Unpacked<T> = T extends IName ? string : T extends ID ? number : T;
type nameType = Unpacked<IName>;
type ElementOf<T> = T extends Array<infer E> ? E : T;
type res1 = ElementOf<string[]>;
type res2 = ElementOf<number[]>;
type res3 = ElementOf<boolean>;
type Foo<T> = T extends { a: infer U; b: infer U } ? U : never;
type res4 = Foo<{ a: string; b: number }>;
- 映射类型
export default {};
interface IPerson {
name: string;
age: number;
}
type ReadonlyTest<T> = {
readonly
[P in keyof T]: T[P];
};
type PartialTest<T> = {
[P in keyof T]?: T[P];
};
interface IPerson2 {
readonly name?: string;
readonly age?: number;
}
type Test<T> = {
-readonly [P in keyof T]-?: T[P];
};
type res = Test<IPerson2>;
interface IPerson3 {
name: string;
age: number;
}
type res1 = Readonly<IPerson3>;
type res2 = Partial<IPerson3>;
- 映射类型 2
export default {};
type Name = "person" | "animal";
type Person = {
name: string;
age: number;
};
type NewType = Record<Name, Person>;
let res: NewType = {
person: {
name: "唐艺昕",
age: 18,
},
animal: {
name: "云梦",
age: 0.4,
},
};
console.log(res);
interface IInfo {
name: string;
age: number;
}
type PartProp = Pick<IInfo, "age">;
let res2: PartProp = {
age: 18,
};
console.log(res2);
- 其他公共类型
export default {};
interface IPerson {
name?: string;
age?: number;
}
let res: IPerson = {
name: "舒畅",
};
let res2: Required<IPerson> = {
name: "舒畅",
age: 18,
};
interface Student {
name: string;
age: number;
score: number;
sex: boolean;
}
type SProps = Omit<Student, "name">;
let res3: SProps = {
age: 19,
score: 100,
sex: false,
};
function add(x: number): void {
console.log(x);
}
function f0(this: object, x: number) {}
function f1(x: number) {}
type T0 = OmitThisParameter<typeof f0>;
type T1 = OmitThisParameter<typeof f1>;
type T2 = OmitThisParameter<string>;
const x: T0 = add;
const y: T1 = add;
const z: T2 = "江疏影";
console.log(x);
console.log(y);
console.log(z);