TypeScript中type的用法

TypeScript 中,type 关键字用于定义类型别名。通过 type,可以为现有类型创建一个新的名称。这对于简化复杂类型、提高代码可读性和避免重复声明类型非常有用。

基本语法

type TypeName = <existing type>;
  • TypeName 是你要定义的类型别名的名称。
  • 是你想要别名的现有类型或类型组合。

type 关键字的使用场景

1. 基本类型别名

你可以为一个基本的类型(如 numberstringboolean 等)定义一个别名:

type Age = number;
type Name = string;

const age: Age = 25;
const name: Name = "Alice";
2. 对象类型别名

type 还可以用来定义对象的结构类型,这通常用于描述具有特定属性的对象。

type Person = {
    name: string;
    age: number;
    greet(): string;
};

const john: Person = {
    name: "John",
    age: 30,
    greet() {
        return `Hello, my name is ${this.name}`;
    }
};

console.log(john.greet());  // Hello, my name is John
3. 联合类型(Union Types)

type 可以用来定义一个值可以是多种类型之一(即联合类型)。

type ID = string | number;

let userId: ID = "abc123";
userId = 456;  // 也可以是数字
4. 交叉类型(Intersection Types)

通过交叉类型,你可以将多个类型组合成一个新的类型。交叉类型会合并类型的所有属性。

type Address = {
    street: string;
    city: string;
};

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

type PersonWithAddress = Person & Address;

const personWithAddress: PersonWithAddress = {
    name: "Alice",
    age: 30,
    street: "123 Main St",
    city: "Wonderland"
};

在上面的例子中,PersonWithAddress 类型是 PersonAddress 类型的交集,意味着它具有两者的所有属性。

5. 函数类型别名

你可以使用 type 来定义函数类型。这样,你可以确保函数的参数和返回值符合预期的类型。

type AddFunction = (a: number, b: number) => number;

const add: AddFunction = (a, b) => a + b;

console.log(add(2, 3));  // 5
6. 可选属性

你可以使用 type 定义对象类型,其中的一些属性是可选的,使用 ? 来标记。

type Person = {
    name: string;
    age?: number;  // 可选属性
};

const person1: Person = { name: "Alice" };
const person2: Person = { name: "Bob", age: 30 };
7. 只读属性(Readonly)

type 还可以定义只读属性,防止对象属性被修改。

type Point = {
    readonly x: number;
    readonly y: number;
};

const point: Point = { x: 10, y: 20 };

// point.x = 30;  // 编译时错误,x是只读属性
8. 类型别名与类型推断

当你定义一个类型别名时,TypeScript 可以推断出一些默认的类型。这样你可以避免显式声明类型,而是让 TypeScript 自动推导。

type StringArray = string[];

const names: StringArray = ["Alice", "Bob"];  // TypeScript 推断出 names 是 string[] 类型
9. 映射类型(Mapped Types)

你可以使用 type 和映射类型的结合来创建新的类型。映射类型根据现有类型的属性生成一个新类型。

type ReadOnly<T> = {
    readonly [K in keyof T]: T[K];
};

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

type ReadOnlyPerson = ReadOnly<Person>;

const person: ReadOnlyPerson = {
    name: "Alice",
    age: 30
};

// person.name = "Bob";  // 错误,name 是只读的

10. 条件类型(Conditional Types)

type 还支持条件类型,它根据类型的条件来选择不同的类型。

type IsString<T> = T extends string ? "Yes" : "No";

type Test1 = IsString<string>;  // "Yes"
type Test2 = IsString<number>;  // "No"

条件类型用于根据某些条件选择类型,常用于处理泛型、类型推断等场景。

11. 索引类型(Index Types)

你可以通过索引类型来表示一个类型的键可以是某种特定类型。

type MyObject = {
    [key: string]: number;
};

const obj: MyObject = {
    age: 25,
    score: 100
};

这表示 MyObject 是一个可以使用字符串作为键,值为 number 类型的对象。

总结

  • type 关键字是 TypeScript 中定义类型别名的主要工具。
  • 使用 type 你可以为基本类型、联合类型、交叉类型、函数类型等创建别名。
  • type 可以与其他 TypeScript 特性(如映射类型、条件类型、索引类型等)结合使用,创建复杂的类型结构。
  • 相比于 interfacetype 具有更高的灵活性,可以定义更多种类的类型,如联合类型、交叉类型和映射类型。

常见场景

  • 当你需要为一个复杂的类型定义简洁的别名时。
  • 在处理联合类型或交叉类型时,type 可以让类型更具可读性和可维护性。
  • 使用条件类型和映射类型来动态生成类型。

你可能感兴趣的:(HarmonyOS,typescript,前端)