·1 min read·技术

TypeScript 实用技巧

分享一些日常开发中常用的 TypeScript 技巧,提高代码质量和开发效率。

类型推断

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">;
<Callout type="success" title="推荐"> 善用这些内置工具类型可以大大减少重复的类型定义。 </Callout>

类型守卫

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 技巧可以帮助你:

  1. 写出更简洁的类型定义
  2. 提高代码的类型安全性
  3. 获得更好的 IDE 支持

多加练习,你会发现 TypeScript 越用越顺手!

相关文章