ts 拾遗
ts交叉类型

ts 拾遗

更新于 2025-03-05
1468

声明函数类型

在 TypeScript 中,声明一个函数为某个类型的几种常见方式:

  1. 使用类型注解声明函数的参数和返回值类型:
typescript
function add(a: number, b: number): number {
return a + b;
}
  1. 使用类型别名声明函数类型:
typescript
type AddFunction = (a: number, b: number) => number;
const add: AddFunction = (a, b) => {
return a + b;
};
  1. 使用接口声明函数类型:
typescript
interface AddFunction {
(a: number, b: number): number;
}
const add: AddFunction = (a, b) => {
return a + b;
};
  1. 使用泛型声明函数类型:
typescript
function identity<T>(arg: T): T {
return arg;
}

Omit 多个属性

在 TypeScript 中,可以使用 "Omit" 工具类型来从一个类型中排除指定的属性。"Omit" 类型接受两个参数:第一个参数是要从中排除属性的类型,第二个参数是要排除的属性名称。

下面是一个示例:

typescript
type Person = {
name: string;
age: number;
address: string;
};
type PersonWithoutAgeAndAddress = Omit<Person, 'age' | 'address'>;
// 使用示例
const person: PersonWithoutAgeAndAddress = {
name: 'John Doe'
};

Omit 工具类型创建了一个名为 PersonWithoutAgeAndAddress 的新类型,它排除了 ageaddress 属性。

提取 React 组件 Props 类型

React.ComponentProps

扩展用 typeof 定义的类型

可以通过使用交叉类型(Intersection Types)来扩展一个类型。例如可以定义一个新的类型 NoteWithSortIndex,它将 Note 类型与一个包含 sortIndex 属性的对象类型结合起来。这样,NoteWithSortIndex 类型就包含了 Note 类型的所有属性,外加一个可选的 sortIndex 属性。可以在需要使用 sortIndex 的地方使用 NoteWithSortIndex 类型,而不需要修改 Note 类型本身。

typescript
export const DEFAULT_NOTE = {
seq: "0",
id: Date.now(),
content: "",
tags: [] as string[],
updatedAt: Date.now(),
};
export type Note = typeof DEFAULT_NOTE;
// 定义一个新的类型,包含可选的 sortIndex 属性
type SortIndex = {
sortIndex?: number;
};
// 使用交叉类型来扩展 Note 类型
export type NoteWithSortIndex = Note & SortIndex;

联合类型(Union Types)

联合类型使用 | 符号将多个类型组合在一起,表示一个值可以是这些类型中的任意一个。联合类型表示“或”的关系,即一个变量可以是多个类型中的某一种。联合类型的变量只能访问多个类型中的共同属性和方法。如果需要访问非共同属性,需要通过类型断言或类型守卫