Ts 工具类型汇总

一、`Omit`

作用:根据现有类型创建一个新的类型,去除不需要的特定属性。

现在我们想要一个新的类型,它与 `Person` 类型相同,但不包含 `address` 属性。可以使用 `Omit` 来实现

interface Person {

  name: string;

  age: number;

  address: string;

  phone: string;

}



type PersonWithoutAddress = Omit<Person, "address">;



const personWithoutAddress: PersonWithoutAddress = {

  name: "John",

  age: 30,

  phone: "1234567890",

};

二、`Pick`

作用:从一个类型中挑选出一组属性,创建一个新的类型。

interface Person {

  name: string;

  age: number;

  address: string;

}

type PersonNameAndAge = Pick<Person, "name" | "age">;

const personNameAndAge: PersonNameAndAge = {

  name: "John",

  age: 30,

};

三、`Partial`

作用:将一个类型的所有属性变为可选的,创建一个新的类型。

interface Person {

  name: string;

  age: number;

  address: string;

}

type PartialPerson = Partial<Person>;

const partialPerson: PartialPerson = {

  name: "John",

};

四、`Required`

作用:将一个类型的所有属性变为必填的,创建一个新的类型。

interface Person {

  name?: string;

  age?: number;

  address?: string;

}

type RequiredPerson = Required<Person>;

const requiredPerson: RequiredPerson = {

  name: "John",

  age: 30,

  address: "Somewhere",

};

五、`Readonly`

作用:将一个类型的所有属性变为只读的,创建一个新的类型。

interface Person {

  name: string;

  age: number;

}

type ReadonlyPerson = Readonly<Person>;

const readonlyPerson: ReadonlyPerson = {

  name: "John",

  age: 30,

};

// 尝试修改会报错

readonlyPerson.name = "Jane";

六、`Record`

作用:创建一个由指定键类型和值类型组成的对象类型。

type Key = string;

type Value = number;

type MyRecord = Record<Key, Value>;



const myRecord: MyRecord = {

  key1: 10,

  key2: 20,

};

七、`Exclude<T, U>`

作用:从类型 `T` 中排除可以赋值给类型 `U` 的类型,返回一个新的类型。

type T1 = Exclude<"a" | "b" | "c", "a" | "b">; // "c"

八、`Extract<T, U>`

作用:从类型 `T` 中提取可以赋值给类型 `U` 的类型,返回一个新的类型。

type T2 = Extract<"a" | "b" | "c", "a" | "b">; // "a" | "b"

九、`NonNullable<T>`

作用:从类型 `T` 中排除 `null` 和 `undefined`,返回一个新的类型。

type T3 = NonNullable<string | null | undefined>; // string

十、`ReturnType<T>`

作用:获取函数类型 `T` 的返回值类型。

type T4 = ReturnType<() => string>; // string

十一、`Parameters<T>`

作用:获取函数类型 `T` 的参数类型组成的元组类型。

type T5 = Parameters<(a: number, b: string) => void>; // [number, string]

十二、`InstanceType<T>`

作用:获取构造函数类型 `T` 的实例类型。

class MyClass {

  prop = "value";

}

type T6 = InstanceType<typeof MyClass>; // MyClass 的实例类型

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yqcoder

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值