ThatManK Mobile Article
补充-2
- 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>;
// infer关键字可以简化操作
type ElementOf<T> = T extends Array<infer E> ? E : T;
type res1 = ElementOf<string[]>;
type res2 = ElementOf<number[]>;
type res3 = ElementOf<boolean>;
// infer关键字可以推断出联合类型
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 // 遍历指定类型所有的key,并添加到当前类型上
// obj = {a: 1} obj[a]
[P in keyof T]: T[P];
};
// type res = ReadonlyTest<IPerson>
// 可选
type PartialTest<T> = {
[P in keyof T]?: T[P];
};
// type res = PartialTest<IPerson>
// 通过 + - 指定添加或者删除
interface IPerson2 {
readonly name?: string;
readonly age?: number;
}
type Test<T> = {
-readonly [P in keyof T]-?: T[P];
};
type res = Test<IPerson2>;
// Readonly / Partial
interface IPerson3 {
name: string;
age: number;
}
type res1 = Readonly<IPerson3>;
type res2 = Partial<IPerson3>;
- 映射类型 2
export default {};
// Record映射类型
// 他会将一个类型的所有属性值都映射到另一个类型上并创造一个新的类型
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);
// Pick映射类型
// 将原有类型中的部分内容映射到新类型中
interface IInfo {
name: string;
age: number;
}
type PartProp = Pick<IInfo, "age">;
let res2: PartProp = {
// name: "韩雪"
age: 18,
};
console.log(res2);
- 其他公共类型
export default {};
// Required<Type>
// 构建一个由 Type 的所有属性组成的类型, 设置为必填.与 Partial 相反
interface IPerson {
name?: string;
age?: number;
}
let res: IPerson = {
name: "舒畅",
};
let res2: Required<IPerson> = {
name: "舒畅",
age: 18,
};
// Omit<Type, Keys>
// Exclude
// 通过从 Type 中选取所有属性, 然后删除 Keys (属性名或属性名的联合)来构造一个类型.
interface Student {
name: string;
age: number;
score: number;
sex: boolean;
}
type SProps = Omit<Student, "name">;
let res3: SProps = {
age: 19,
score: 100,
sex: false,
};
// OmitThisParameter
// 从类型T中剔除this参数类型, 并构造一个 新类型
function add(x: number): void {
console.log(x);
}
function f0(this: object, x: number) {}
function f1(x: number) {}
// (x: number) => void
type T0 = OmitThisParameter<typeof f0>;
// (x: number) => void
type T1 = OmitThisParameter<typeof f1>;
// string
type T2 = OmitThisParameter<string>;
const x: T0 = add;
const y: T1 = add;
const z: T2 = "江疏影";
console.log(x);
console.log(y);
console.log(z);