Typescript高级类型
类型操作符
- keyof Type
从Type中提取key,形成新的类型
type Point = { x: number; y: number };
type P = keyof Point;
// =>
type P = 'x' | 'y';
- typeof Type
let s = "hello";
type N = typeof s;
// =>
type N = string;
- ! 操作符
非空断言操作符,当使用**!** 时,要确保指定的值不会为null或者undefined
function liveDangerously(x?: number | null) {
// No error
console.log(x!.toFixed());
}
类型工具
- Partial<Type>
将Type类型的属性全部变成可选
interface Todo {
title: string;
description: string;
}
type NewTodo = Partial<Todo>;
// =>
interface NewTodo {
title?: string;
description?: string;
}
- Record<Keys, Type>
组合Keys和Type类型,形成新的类型
interface CatInfo {
age: number;
breed: string;
}
type CatName = "miffy" | "boris" | "mordred";
const cats: Record<CatName,CatInfo>;
// =>
interface NewCatInfo {
miffy: CatInfo;
boris: CatInfo;
mordred: CatInfo;
}
- Pick<Keys, Type>
从Type中基于Keys提取一组属性,形成新的类型
interface Todo {
title: string;
description: string;
completed: boolean;
}
type TodoPreview = Pick<Todo, "title" | "completed">;
// =>
interface NewTodo {
title: string;
completed: boolean;
}
- Omit<Type, Keys>
和Pick类似,从Type中忽略Keys属性,形成新的类型
interface Todo {
title: string;
description: string;
completed: boolean;
}
type TodoPreview = Omit<Todo, "title" | "completed">;
// =>
interface NewTodo {
description: string;
}
- Exclude<Type, ExcludedUnion>
从Type中排除ExcludedUnion成员
type T0 = Exclude<"a" | "b" | "c", "a">;
type T1 = Exclude<string | number | (() => void), Function>;
// =>
type T0 = "b" | "c"
type T1 = string | number
- Extract<Type, Union>
提取Type和Union中公共的成员
type T0 = Extract<"a" | "b" | "c", "a" | "f">;
type T1 = Extract<string | number | (() => void), Function>;
// =>
type T0 = "a";
type T1 = () => void;
- Parameters<Type>
从函数类型中获取参数类型,Type必须是函数类型
declare function f1(arg: { a: number; b: string }): void;
type T0 = Parameters<() => string>;
type T1 = Parameters<(s: string) => void>;
type T2 = Parameters<<T>(arg: T) => T>;
type T3 = Parameters<typeof f1>;
// =>
type T0 = [];
type T1 = [s: string];
type T2 = [arg: unknown];
type T3 = [arg: {
a: number;
b: string;
}];
- ReturnType<Type>
和Parameters类似,从函数类型中获取返回值类型,Type必须是函数类型
declare function f1(): { a: number; b: string };
type T0 = ReturnType<() => string>;
type T1 = ReturnType<(s: string) => void>;
type T2 = ReturnType<<T>() => T>;
type T3 = ReturnType<<T extends U, U extends number[]>() => T>;
type T4 = ReturnType<typeof f1>;
type T5 = ReturnType<any>;
type T6 = ReturnType<never>;
// =>
type T0 = string;
type T1 = void;
type T2 = unknown;
type T3 = number[];
type T4 = {
a: number;
b: string;
};
type T5 = any;
type T6 = never;