1. 类型别名和接口

类型别名是为类型起一个新名字,可以用于简化复杂的类型,例如:

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

type UserId = string | number;

接口是用于定义对象的类型,例如:

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

interface IGetUser {
  (id: UserId): User;
}
  1. 泛型

泛型是用于创建可重用代码的工具,可以将类型作为参数传递给函数或类,例如:

function identity<T>(arg: T): T {
  return arg;
}

const result = identity<string>("hello");
  1. 类型守卫

类型守卫是用于在代码中判断类型的工具,例如:

function isString(value: any): value is string {
  return typeof value === "string";
}

function printValue(value: string | number): void {
  if (isString(value)) {
    console.log(value.toUpperCase());
  } else {
    console.log(value.toFixed(2));
  }
}
  1. 索引类型和映射类型

索引类型和映射类型是用于操作对象类型的工具,例如:

type Key = "name" | "age";

type Person = {
  [k in Key]: string | number;
};

type ReadonlyPerson = Readonly<Person>;
  1. 类型推导

类型推导是用于自动推断变量类型的工具,例如:

const name = "John"; // name 的类型被推导为 string
const age = 30; // age 的类型被推导为 number
  1. 可选链操作符

可选链操作符是用于安全访问对象属性的工具,例如:

const user = {
  name: "John",
  address: {
    city: "New York",
  },
};

const city = user?.address?.city;
  1. 枚举类型

枚举类型是用于定义一组有限的常量的工具,例如:

enum Color {
  Red = 1,
  Green = 2,
  Blue = 3,
}

const colorName = Color[2]; // colorName 的值为 "Green"
``
typescript常用的高级用法

原文地址: https://www.cveoy.top/t/topic/ewM0 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录