声明函数类型
在 TypeScript 中,声明一个函数为某个类型的几种常见方式:
- 使用类型注解声明函数的参数和返回值类型:
typescriptfunction add(a: number, b: number): number {return a + b;}
- 使用类型别名声明函数类型:
typescripttype AddFunction = (a: number, b: number) => number;const add: AddFunction = (a
在 TypeScript 中,声明一个函数为某个类型的几种常见方式:
typescriptfunction add(a: number, b: number): number {return a + b;}
typescripttype AddFunction = (a: number, b: number) => number;const add: AddFunction = (a
typescriptinterface AddFunction {(a: number, b: number): number;}const add: AddFunction = (a, b) => {return a + b;};
typescriptfunction identity<T>(arg: T): T {return arg;}
在 TypeScript 中,可以使用 "Omit" 工具类型来从一个类型中排除指定的属性。"Omit" 类型接受两个参数:第一个参数是要从中排除属性的类型,第二个参数是要排除的属性名称。
下面是一个示例:
typescripttype Person = {name: string;age: number;address: string;};type PersonWithoutAgeAndAddress = Omit<Person, 'age' | 'address'>;// 使用示例const person: PersonWithoutAgeAndAddress = {name: 'John Doe'};
Omit 工具类型创建了一个名为 PersonWithoutAgeAndAddress 的新类型,它排除了 age 和 address 属性。
React.ComponentProps
可以通过使用交叉类型(Intersection Types)来扩展一个类型。例如可以定义一个新的类型 NoteWithSortIndex,它将 Note 类型与一个包含 sortIndex 属性的对象类型结合起来。这样,NoteWithSortIndex 类型就包含了 Note 类型的所有属性,外加一个可选的 sortIndex 属性。可以在需要使用 sortIndex 的地方使用 NoteWithSortIndex 类型,而不需要修改 Note 类型本身。
typescriptexport const DEFAULT_NOTE = {seq: "0",id: Date.now(),content: "",tags: [] as string[],updatedAt: Date.now(),};export type Note = typeof DEFAULT_NOTE;// 定义一个新的类型,包含可选的 sortIndex 属性type SortIndex = {
联合类型使用 | 符号将多个类型组合在一起,表示一个值可以是这些类型中的任意一个。联合类型表示“或”的关系,即一个变量可以是多个类型中的某一种。联合类型的变量只能访问多个类型中的共同属性和方法。如果需要访问非共同属性,需要通过类型断言或类型守卫
更新于2026-10-18
更新于2026-10-18
更新于2026-10-18