类型推断
TypeScript 的类型推断非常强大,善用它可以减少冗余代码。
自动推断
typescript
// 不需要显式声明类型
const name = "Neo"; // 自动推断为 string
const age = 25; // 自动推断为 number
const items = [1, 2, 3]; // 自动推断为 number[]使用 as const#
typescript
// 普通对象
const config = {
theme: "dark",
version: 1,
};
// 类型: { theme: string; version: number; }
// 使用 as const
const configConst = {
theme: "dark",
version: 1,
} as const;
// 类型: { readonly theme: "dark"; readonly version: 1; }实用类型工具
Partial<T> 和 Required<T>#
typescript
interface User {
name: string;
email: string;
age?: number;
}
// 所有属性变为可选
type PartialUser = Partial<User>;
// 所有属性变为必需
type RequiredUser = Required<User>;Pick<T, K> 和 Omit<T, K>#
typescript
interface Article {
id: number;
title: string;
content: string;
author: string;
createdAt: Date;
}
// 只选取部分属性
type ArticlePreview = Pick<Article, "id" | "title">;
// 排除部分属性
type ArticleWithoutDates = Omit<Article, "createdAt">;类型守卫
typeof 守卫#
typescript
function process(value: string | number) {
if (typeof value === "string") {
// 这里 value 被推断为 string
return value.toUpperCase();
}
// 这里 value 被推断为 number
return value * 2;
}自定义类型守卫
typescript
interface Cat {
meow(): void;
}
interface Dog {
bark(): void;
}
function isCat(animal: Cat | Dog): animal is Cat {
return (animal as Cat).meow !== undefined;
}
function handleAnimal(animal: Cat | Dog) {
if (isCat(animal)) {
animal.meow(); // TypeScript 知道这是 Cat
} else {
animal.bark(); // TypeScript 知道这是 Dog
}
}泛型技巧
泛型约束
typescript
// 确保 T 有 length 属性
function getLength<T extends { length: number }>(item: T): number {
return item.length;
}
getLength("hello"); // OK
getLength([1, 2, 3]); // OK
getLength({ length: 10 }); // OK
// getLength(123); // Error!条件类型
typescript
type IsString<T> = T extends string ? true : false;
type A = IsString<string>; // true
type B = IsString<number>; // false模板字面量类型
typescript
type Color = "red" | "green" | "blue";
type Size = "small" | "medium" | "large";
// 组合生成所有可能的类名
type ButtonClass = `btn-${Color}-${Size}`;
// "btn-red-small" | "btn-red-medium" | ... 共9种总结
这些 TypeScript 技巧可以帮助你:
- 写出更简洁的类型定义
- 提高代码的类型安全性
- 获得更好的 IDE 支持
多加练习,你会发现 TypeScript 越用越顺手!
