返回

TypeScript中的类型声明:掌握少用但强大的声明方式

前端

TypeScript作为一门强大的类型化语言,为开发人员提供了丰富的类型声明功能。在众多声明方式中,有一些相对不常见,但能有效提升代码健壮性和可读性。本文将深入探讨TypeScript中鲜为人知的类型声明方式,帮助开发者进一步提升代码质量。

基础的分型声明

分型声明是一种允许类型在运行时根据特定条件进行更改的声明方式。通过使用分型声明,开发者可以避免在条件语句中显式检查类型,从而简化代码逻辑。

例如:

type Status = "Active" | "Inactive";

const getStatus = (user: { status: Status }): Status => {
  if (user.status === "Active") {
    return "Active";
  } else {
    return "Inactive";
  }
};

使用分型声明,我们可以将条件逻辑简化为:

type Status = "Active" | "Inactive";

const getStatus = (user: { status: Status }): Status => user.status;

防止获取object时候输入错误key

在获取对象属性时,如果输入了错误的键名,编译器通常不会报错。为了防止这种情况,我们可以使用索引类型来对对象属性进行类型检查。

例如:

type User = {
  name: string;
  age: number;
};

const getUserInfo = (user: User, key: keyof User): string | number => {
  return user[key];
};

通过使用索引类型,编译器会在获取对象属性时进行类型检查,如果输入了错误的键名,将会报错。

创建new Class 模板字符串类型

模板字符串类型允许开发者创建动态类型。在TypeScript中,我们可以利用模板字符串类型来创建new class的类型。

例如:

type NewClassType<T> = new (...args: any[]) => T;

const MyClass = class {
  constructor(name: string) {
    this.name = name;
  }
};

const MyClassType: NewClassType<MyClass> = MyClass;

基础映射类型

映射类型允许开发者将一个类型的属性映射到另一个类型。这在需要转换对象类型时非常有用。

例如:

type User = {
  name: string;
  age: number;
};

type ReadonlyUser = {
  readonly name: string;
  readonly age: number;
};

const convertUserToReadOnly = (user: User): ReadonlyUser => {
  return {
    name: user.name,
    age: user.age,
  };
};

映射修饰符

TypeScript提供了几个映射修饰符,可以用来修改映射类型中的属性。这些修饰符包括:

  • readonly:将属性标记为只读
  • optional:将属性标记为可选
  • ?:将属性标记为可选(与optional等效)
  • +:将属性标记为必填(与required等效)

例如:

type User = {
  name: string;
  age: number;
};

type PartialUser = {
  name?: string;
  age?: number;
};

添加-或前缀来删除或添加这些修饰符

可以通过在修饰符前添加-+前缀来删除或添加这些修饰符。

例如:

type User = {
  name: string;
  age: number;
};

type RequiredUser = {
  -readonly name: string;
  -optional age: number;
};

键重映射

键重映射允许开发者指定键的优先级。这在需要从联合类型中提取特定属性时非常有用。

例如:

type User = {
  name: string;
  age: number;
};

type Profile = {
  avatar: string;
  bio: string;
};

type UserOrProfile = User | Profile;

const getUserInfo = (userOrProfile: UserOrProfile): string => {
  if ("name" in userOrProfile) {
    return userOrProfile.name;
  } else {
    return userOrProfile.avatar;
  }
};

通过类型根据输入值判断获取类型

我们可以利用类型保护来根据输入值判断获取类型。这在需要根据条件获取不同类型的返回值时非常有用。

例如:

type User = {
  name: string;
  age: number;
};

type Profile = {
  avatar: string;
  bio: string;
};

const getUserInfo = (input: User | Profile): string => {
  if (typeof input === "object" && "name" in input) {
    return input.name;
  } else {
    return input.avatar;
  }
};

总之,虽然这些类型声明方式在TypeScript中相对不常见,但它们可以有效提升代码健壮性和可读性。通过掌握这些声明方式,开发者可以编写出更优雅、更可维护的代码。