前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >typescript 入门-工具类型

typescript 入门-工具类型

作者头像
copy_left
发布2021-06-11 18:12:54
4550
发布2021-06-11 18:12:54
举报
文章被收录于专栏:方球方球

type 类型别名

代码语言:javascript
复制
// 为某类型指定别名
type Name = string
type Age = number
type Man = {
  name: Name
  age: Age
}

const c: Man = {
  name: 'c',
  age: 20
}

keyof 对象键类型

代码语言:javascript
复制
type _Object = { [key: string]: unknown }

function getKeysByObj<T extends _Object>(o: T): (keyof T)[]{
  return Object.keys(o)
}

const a = {
  name: 'a',
  age: 12
}

const aKeys = getKeysByObj(a)
// aKeys: ('name' | 'age')[]

const b = {
  1: 'b',
  2: 20
}

const bKeys = getKeysByObj(b)
// bKeys: (1|2)[]

typeof 值类型

代码语言:javascript
复制
const a = {
  name: 'a',
  age: 23
}
// 通过 typeof b 获取 a的类型定义
const b: typeof a = {
  name: 'b',
  age: 10
}

/**
 * a 类型定义
 * {
 *   name: string,
 *   age: number
 *  }
 */

// 获取函数定义
function random(n: number): number{
  return Math.random() * n
}

type Random = typeof random
// (n:number) => number

Partial<T> 转为可选参数

代码语言:javascript
复制
interface Man {
  name: string,
  age: number
}
// 将Man的所有属性改为可选
type ManCopy = Partial<Man>

const cache: ManCopy = {}
// ManCopy { name?: string, age?: number }

Required<T> 将属性全转为必填

代码语言:javascript
复制
interface Data {
  id: string
  type?: string
}

type FullData = Required<Data>

const fd: FullData = {
  id: 'xx',
  type: 'su'
}

Readonly <T> 属性都转为只读

代码语言:javascript
复制
interface Data {
  id: string
  type?: string
}

type ReadonlyData = Readonly<Data>

const d:ReadonlyData = {
  id: 'xx',
}

d.id = 'cc'
//  Cannot assign to 'id' because it is a read-only property.

Record<K, T> 定义 K 为键, T 为值的映射类型

代码语言:javascript
复制
type keys = 'name' | 'job' | 'age'
type Man = Record<keys, string>

const m: Man = {
  name: 'm',
  job: 't',
  age: '10',
}

/**
 * {
 *  name: string,
 *  job: string,
 *  age: string
 * }
 */

Pick 提取指定属性,生成新类型

代码语言:javascript
复制
interface Man {
  id: string
  name: string
  age: number
  job: string
  birth: string
  address: string
}

// 提取指定属性类型
type ManIt = Pick<Man, 'name' | 'age' | 'job'>

const m: ManIt = {
  name: 'm',
  age: 25,
  job: 'tt'
}

/**
 * {
 *   name: string,
 *   age: number,
 *   job: string
 * }
 */

Omit 删除指定属性,生成新类型

代码语言:javascript
复制
type A = 'color' | 'width' | 'height'
type B = {
  name: string
  width: number
  height: number
}

type C = Omit<B, A>
// { name: string }

Exclude<K, T> 联合类型取 K,T 的差集

代码语言:javascript
复制
interface A{
  name: string
  color: string
}

interface B{
  name: string,
  width: number
}

type keys = Exclude<keyof A, keyof B>
type C = Record<keys, string>

const c: C = {
  color: 'orange'
}

/**
 * {
 *  color: string
 * }
 */

Extract<A, B> 联合类型取 A, B的并集

代码语言:javascript
复制
type A = 'color' | 'width' | 'height'
type B = 'name' | 'height'
type C = Extract<A, B>
// "height"

NonNullable 过滤类型内的 null 、 undefined、never

代码语言:javascript
复制
type A = 'data' | null | undefined | never
type B = NonNullable<A>
// type "data"

type T1 = NonNullable<null>
// never
type T2 = NonNullable<undefined>
// never
type T3 = NonNullable<never>
// nerver
type T4 = NonNullable<any>
// any
type T5 = NonNullable<string>
// string

Parameters<FN> 获取函数参数类型元组

代码语言:javascript
复制
function buildCar(name: string, color: string){
  return { name, color }
}

const args: Parameters<typeof buildCar> = ['xx', 'yy']
// ('string', 'string')

console.log(buildCar(...args))
// { name: 'xx', color: 'yy'

ConstructorParameters<constructor> 获取构造函数参数类型元组

代码语言:javascript
复制
class Car{
  name:string
  color:string

  constructor(name: string, color:string){
    this.name = name
    this.color = color
  }

}

interface CarConstructor{
  new (name: string, color:string): Car
}

const args:ConstructorParameters<CarConstructor> = ['mini', 'blue']
// type ['string', 'string']

const c = new Car(...args)

InstanceType<constructor> 获取构造函数返回值类型

代码语言:javascript
复制
class Car{
  name:string
  color:string

  constructor(name: string, color:string){
    this.name = name
    this.color = color
  }

}

interface CarConstructor{
  new (name: string, color:string): Car
}

type c = InstanceType<CarConstructor>
// type Car

ReturnType<T> 函数返回值类型

代码语言:javascript
复制
function getNumber(): number{
  return Math.random()
}

function getString(): string{
  return `${Math.random()}`
}

let a:ReturnType<typeof getNumber>
let b: ReturnType<typeof getString>

a = 10
b = 'msg'

Uppercase 字符字面量全大写

代码语言:javascript
复制
type Status = 'success' | 'fail'
type STATUS = Uppercase<Status>
// type "SUCCESS" | "FAIL"

Lowercase 字符字面量全小写

代码语言:javascript
复制
type Status = "SUCCESS" | "FAIL"
type status = Lowercase<Status>
// type "success" | "fail"

Capitalize 字符字面量首字母大写

代码语言:javascript
复制
type Status = "success" | "FAIL"
type status = Capitalize<Status>
// type "FAIL" | "Success"

UnCapitalize 字符字面量首字母小写

代码语言:javascript
复制
type Status = "success" | "FAIL"
type status = Uncapitalize<Status>
// type "success" | "fAIL"

ThisType 明确当前函数this的指向类型

代码语言:javascript
复制
// 没有ThisType情况下
const foo = {
    bar() {
         console.log(this.a); // error,在foo中只有bar一个函数,不存在a
    }
}

// 使用ThisType
const foo: { bar: any } & ThisType<{ a: number }> = {
    bar() {
         console.log(this.bar) // error,因为没有在ThisType中定义
         console.log(this.a); // ok
    }
}

foo.bar // ok
foo.a // error,在外面的话,就跟ThisType没有关系了

ThisParameterType 获取函数this指向类型

代码语言:javascript
复制
interface Car{
  name: string
  color: string
}

function getCarName(this: Car){
  console.log(this.name)
}

const c = {
  name: 'x',
  color: 'y',
}

getCarName.apply(c)
// x

type T = ThisParameterType<typeof getCarName>
// type Car
// 函数 getCarName this 类型指向Car

OmitThisParameter 获取一个没有this指向的函数类型

代码语言:javascript
复制
interface Car{
  name: string
  color: string
}

function getCarName(this: Car){
  console.log(this.name)
}

type T = OmitThisParameter<typeof getCarName>
// type () => void

const fn: T = () => {
  console.log('not name')
}

infer 替代推断类型

代码语言:javascript
复制
type Unpacked<T> =  T extends (infer U)[] ? U : T;

type T0 = Unpacked<string[]>; // string
type T1 = Unpacked<string>; // string

文档

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • type 类型别名
  • keyof 对象键类型
  • typeof 值类型
  • Partial<T> 转为可选参数
  • Required<T> 将属性全转为必填
  • Readonly <T> 属性都转为只读
  • Record<K, T> 定义 K 为键, T 为值的映射类型
  • Pick 提取指定属性,生成新类型
  • Omit 删除指定属性,生成新类型
  • Exclude<K, T> 联合类型取 K,T 的差集
  • Extract<A, B> 联合类型取 A, B的并集
  • NonNullable 过滤类型内的 null 、 undefined、never
  • Parameters<FN> 获取函数参数类型元组
  • ConstructorParameters<constructor> 获取构造函数参数类型元组
  • InstanceType<constructor> 获取构造函数返回值类型
  • ReturnType<T> 函数返回值类型
  • Uppercase 字符字面量全大写
  • Lowercase 字符字面量全小写
  • Capitalize 字符字面量首字母大写
  • UnCapitalize 字符字面量首字母小写
  • ThisType 明确当前函数this的指向类型
  • ThisParameterType 获取函数this指向类型
  • OmitThisParameter 获取一个没有this指向的函数类型
  • infer 替代推断类型
  • 文档
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档