深入理解 TypeScript:工具类型和关键字

101 阅读2分钟

前言

TypeScript 是 JavaScript 的一个超集,它引入了静态类型检查和一些其他的 JavaScript 不具备的功能,从而提高了代码的可读性和可维护性。在 TypeScript 中,有许多工具类型和关键字可以帮助我们更好地处理类型。在本文中,我们将深入探讨一些常见的 TypeScript 工具类型和关键字。

关键字

keyof

keyof 关键字可以获取一个类型的所有属性的名称。

type UserKeys = keyof User; // 'name' | 'age'

typeof

typeof 关键字可以获取一个变量的类型。

const user = { name: 'Alice', age: 20 };

type UserType = typeof user; // { name: string, age: number }

as

as 关键字可以用于类型断言,告诉编译器一个变量的实际类型。

const input = document.querySelector('#my-input') as HTMLInputElement;

enum

enum 关键字用于创建枚举类型,枚举类型是一种包含固定数量值的特殊类型

enum Color {
  Red,
  Green,
  Blue
}
let c: Color = Color.Green;

extends

extends 关键字用于定义一个类继承另一个类,或者一个接口继承另一个接口。

class Animal {
  name: string;
}

class Dog extends Animal {
  breed: string;
}

implements

implements 关键字用于实现一个接口。

interface ClockInterface {
  tick(): void;
}

class Clock implements ClockInterface {
  tick() {
    console.log("tick tock");
  }
}

工具类型

Partial

Partial<T> 类型可以将一个类型的所有属性都变为可选。这对于处理可能存在的对象非常有用。

interface User {
  name: string;
  age: number;
}

const user: Partial<User> = { name: 'Alice' };

ReadOnly

Readonly<T> 类型可以将一个类型的所有属性都变为只读。这可以确保对象的属性不会被修改。

const user: Readonly<User> = { name: 'Alice', age: 20 };

user.age = 21; // Error: Cannot assign to 'age' because it is a read-only property

Pick

Pick<T, K extends keyof T> 类型可以从一个类型中挑选出一些属性,创建一个新的类型。

type UserAge = Pick<User, 'age'>; // { age: number }

Record

Record<K extends keyof any, T> 类型可以将一个类型的所有属性值都转换为另一种类型。

type PageInfo = Record<'title' | 'description', string>;

const page: PageInfo = {
  title: 'Home',
  description: 'Welcome to our website',
};

Exclude

Exclude<T, U> 类型可以从 T 中排除出可以赋值给 U 的类型。

type T0 = Exclude<"a" | "b" | "c", "a">;  // "b" | "c"
type T1 = Exclude<"a" | "b" | "c", "a" | "b">;  // "c"

Extract

Extract<T, U> 类型可以从 T 中提取出可以赋值给 U 的类型。

type T0 = Extract<"a" | "b" | "c", "a" | "f">;  // "a"
type T1 = Extract<string | number | (() => void), Function>;  // () => void

ReturnType

ReturnType<T> 类型可以获取一个函数返回值的类型。

type T0 = ReturnType<() => string>;  // string
type T1 = ReturnType<(s: string) => void>;  // void

InstanceType

InstanceType<T> 类型可以获取一个构造函数类型的实例类型。

class C {
  x = 0;
  y = 0;
}

type T0 = InstanceType<typeof C>;  // C
type T1 = InstanceType<any>;  // any
type T2 = InstanceType<never>;  // any