
收集了一些日常开发中常用的 TypeScript 技巧。
类型工具
Partial & Required
interface User {
name: string;
age: number;
email: string;
}
type PartialUser = Partial<User>; // 所有属性可选
type RequiredUser = Required<User>; // 所有属性必填
Pick & Omit
type UserName = Pick<User, 'name' | 'email'>;
type UserWithoutEmail = Omit<User, 'email'>;
泛型技巧
条件类型
type IsString<T> = T extends string ? true : false;
type A = IsString<"hello">; // true
type B = IsString<42>; // false
infer 关键字
type ReturnType<T> = T extends (...args: any[]) => infer R ? R : never;
实用模式
类型守卫
function isString(value: unknown): value is string {
return typeof value === 'string';
}
模板字面量类型
type Color = 'red' | 'blue' | 'green';
type CSSColor = `--color-${Color}`;
// "--color-red" | "--color-blue" | "--color-green"
const 断言
const config = {
api: '/api',
timeout: 5000,
} as const;
// 类型变为 { readonly api: "/api"; readonly timeout: 5000; }
常见错误
- 不要过度使用
any,用unknown代替 - 避免类型断言
as,优先使用类型守卫 - 善用严格模式
"strict": true
