TypeScript中的几个方法

TypeScript中的几个方法

TypeScript 中的类型系统是非常强大的。它为我们提供了类型安全。类型系统虽然受人喜爱,但如果我们不规划和设计类型和接口,它也会让我们的代码变得混乱难读。

泛型

避免代码重复中,创建可重用的类型,是我们编写简洁代码重要的一环。泛型是 TypeScript 的一个功能,它允许我们编写可重用的类型。看下面的例子:


type Add<T> = (a: T, b: T) => T

const addNumbers: Add<number> = (a, b) => {
  return a + b
}

const addStrings: Add<string> = (a, b) => {
  return a + b
}

实用类型

Pick<Type, Keys>

Pick会从 Type 中挑选属性集 Keys 来创建一个新的类型,Keys 可以是一个字符串字面或字符串字面的联合。Keys 的值必须是 Type 的键,否则TypeScript编译器会抱怨。当你想通过从有很多属性的对象中挑选某些属性来创建更轻的对象时,这个实用类型特别有用。


type User = {
  name: string
  age: number
  address: string
  occupation: string
}

type BasicUser = Pick<User, "name" | "age">

// type BasicUser = {
//   name: string;
//   age: number;
// }

Omit<Type, Keys>

OmitPick相反。 Keys 不是说要保留哪些属性,而是指要省略的属性键集。 当我们只想从对象中删除某些属性并保留其他属性时,这个会更有用。


type User = {
  name: string
  age: number
  address: string
  occupation: string
}

type BasicUser = Omit<User, "address" | "occupation">

// type BasicUser = {
//   name: string;
//   age: number;
// }

Partial

Partial 构造了一个类型,其所有的类型属性都设置为可选。当我们在编写一个对象的更新逻辑时,这个可能非常有用。


type User = {
  name: string
  age: number
  address: string
  occupation: string
}

type PartialUser = Partial<User>

// type PartialUser = {
//   name?: string;
//   age?: number;
//   address?: string;
//   occupation?: string;
// }

Required

RequiredPartial相反。它构造了一个类型的所有属性都是必填的类型。它可以被用来确保在一个类型中没有可选属性出现。


type PartialUser = {
  name: string
  age: number
  address?: string
  occupation?: string
}

type User = Required<PartialUser>

// type User = {
//   name: string;
//   age: number;
//   address: string;
//   occupation: string;
// }

Readonly

Readonly 构建了一个类型,其类型的所有属性被设置为只读。重新分配新的值 TS 就会报错。

type User = {
  name: string
  age: number
  address: string
  occupation: string
}

type ReadOnlyUser = Readonly<User>

const user: ReadOnlyUser = {
  name: "小智",
  age: 24,
  address: "厦门",
  occupation: "大迁世界"
}

user.name = "王大冶"
// Cannot assign to 'name' because it is a read-only property.

ReturnType

ReturnType 从一个函数类型的返回类型构建一个类型。当我们处理来自外部库的函数类型并希望基于它们建立自定义类型时,它是非常有用的。


import axios from 'axios'

type Response = ReturnType<typeof axios>

function callAPI(): Response{
  return axios("url")
}

More

更多TS方法可以在 这里

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值