郭佳恩前端工程师
返回首页
20 分钟阅读技术专栏

TypeScript 类型体操:从入门到精通

掌握 TypeScript 高级类型系统是区分初级和高级前端工程师的关键。本文深入讲解泛型、条件类型、映射类型以及 infer 关键字的妙用。

TypeScriptProgrammingFrontend

TypeScript 的类型系统是图灵完备的。这意味着你可以用类型系统本身来编写逻辑。

1. 实现 Pick 和 Omit

了解内置工具类型的原理:

typescript
type MyPick<T, K extends keyof T> = {
  [P in K]: T[P];
};

type MyOmit<T, K extends keyof T> = MyPick<T, Exclude<keyof T, K>>;

interface User {
  id: number;
  name: string;
  email: string;
}

type UserPreview = MyPick<User, 'id' | 'name'>;
// { id: number; name: string; }

2. 条件类型与 infer

infer 关键字允许我们在条件类型中推断类型变量。

typescript
// 获取函数返回值的类型
type MyReturnType<T> = T extends (...args: any[]) => infer R ? R : any;

function getUser() {
  return { id: 1, name: 'Alice' };
}

type UserType = MyReturnType<typeof getUser>;
// { id: number; name: string; }

3. 递归类型

实现一个深度只读类型 DeepReadonly

typescript
type DeepReadonly<T> = {
  readonly [P in keyof T]: T[P] extends object 
    ? DeepReadonly<T[P]> 
    : T[P];
};

interface NestedObj {
  a: {
    b: {
      c: string;
    };
  };
}

type ReadonlyObj = DeepReadonly<NestedObj>;
// ReadonlyObj.a.b.c 也是只读的

4. 模板字面量类型

typescript
type World = "world";
type Greeting = `hello ${World}`; // "hello world"

type CssPadding = `padding-${"top" | "bottom" | "left" | "right"}`;
// "padding-top" | "padding-bottom" | "padding-left" | "padding-right"

评论区0

自由讨论你的想法,分享你的实践。

还没有评论

成为第一个发言的人吧