Skip to content

方括号操作符(Index Signature 和类型查询)

在 TypeScript 中,方括号操作符有多种用途,最常见的是用于访问对象的属性和定义索引签名。此外,方括号操作符还用于类型查询(Type Query),允许你从现有类型中提取信息。下面我们详细探讨这些用法。

1. 访问对象属性

方括号操作符最常见的用途是动态访问对象的属性。通过使用字符串或变量作为键,你可以灵活地获取对象的属性值。

示例

typescript
const obj = {
  name: "Alice",
  age: 30,
};

// 使用字符串字面量
console.log(obj["name"]); // 输出: Alice

// 使用变量
const key = "age";
console.log(obj[key]); // 输出: 30

2. 定义索引签名 (Index Signatures)

索引签名允许你定义一个对象类型,其中键可以是任意字符串或数字,并且每个键对应的值都必须符合指定的类型。

字符串索引签名

typescript
interface StringIndexed {
  [key: string]: any;
}

const obj: StringIndexed = {
  name: "Alice",
  age: 30,
  extraProperty: true, // OK, 因为 [key: string]: any 存在
};

数字索引签名

typescript
interface NumberIndexed {
  [key: number]: string;
}

const obj: NumberIndexed = {
  0: "zero",
  1: "one",
};

3. 类型查询 (Type Queries)

类型查询允许你从现有类型中提取信息。它使用 typeof 关键字与方括号操作符结合来创建新的类型。

语法

typescript
type TypeName = typeof variableName;

示例:从变量中提取类型

typescript
const message = "Hello, world!";
type MessageType = typeof message; // string

在这个例子中,MessageType 被推导为 string 类型,因为 message 的类型是 string

示例:从模块中提取类型

typescript
import { someFunction } from "some-module";

type FunctionType = typeof someFunction;

在这个例子中,FunctionType 将被推导为 someFunction 的函数签名类型。

4. 条件类型中的类型查询

类型查询还可以在条件类型中使用,以实现更复杂的类型操作。

示例:从实例中提取构造函数类型

typescript
class MyClass {}

type ConstructorType = typeof MyClass; // typeof MyClass 是构造函数类型

在这个例子中,ConstructorType 被推导为 MyClass 的构造函数类型。

示例:从对象中提取属性类型

typescript
interface Person {
  name: string;
  age: number;
}

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

type NameType = (typeof person)["name"]; // string
type AgeType = (typeof person)["age"]; // number

在这个例子中,NameType 被推导为 string 类型,AgeType 被推导为 number 类型。

5. 映射类型的类型查询

在映射类型中,类型查询可以帮助你在遍历对象属性时保持类型信息。

示例:映射类型的类型查询

typescript
type Keys = "name" | "age";
type Values = string | number;

type Person = {
  [K in Keys]: Values;
};

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

type NameType = (typeof person)["name"]; // string | number

在这个例子中,Person 是一个映射类型,NameType 被推导为 string | number 类型。

6. 注意事项

  • 类型安全:使用方括号操作符访问对象属性时,确保提供的键名是有效的,以避免运行时错误。

  • 性能考虑:虽然类型查询提供了强大的类型推导能力,但在大型项目中应权衡其对编译时间和复杂度的影响。

  • 意图清晰:在设计类型查询时,尽量保持意图清晰,避免过度复杂的类型操作,提高代码的可读性和维护性。

总结

方括号操作符在 TypeScript 中不仅用于访问对象属性和定义索引签名,还可以用于类型查询,帮助你从现有类型中提取信息。通过合理使用方括号操作符,你可以编写出更加灵活且类型安全的代码。

Released under the MIT License.