📕
余烬的小册
数据结构与算法GitHub
  • 总述
  • 经验记录
    • 经验总结
      • web component
      • 前端性能优化总结与分析
      • 我的长列表优化方案
      • 双向通讯解决方案
      • 🔧基于istanbul实现代码测试覆盖率工具
      • 表单系统(低代码表单)
      • 跨端小程序
      • 设计一个即时聊天功能
      • 跨页面通讯 3658699fe4cb4d0bbe22b0881390bacd
    • 踩坑记录
      • HTML踩坑记录
      • Flutter踩坑记录
      • CSS踩坑记录
  • 源码解析
    • Vue源码解析
      • Vue2源码解析系列-响应式原理
      • Vue2源码解析系列-模板编译
      • Vue2源码解析系列-渲染系统(待更新)
        • Patch
      • Vue2源码解析系列-调度系统(todo)
      • Vue2组件更新流程(todo)
      • 如何学习Vue源码
      • Vue3源码解析系列-响应系统
      • Vue3源码解析系列-渲染系统
      • Vue3源码解析系列-组件化和渲染优化(todo)
      • Vue router源码解析(todo)
    • React源码解析(todo)
    • 微前端
      • qiankun源码解析(todo)
    • Vite源码解析
      • Vite Client源码
      • Vite Server源码(todo)
  • 前端技术
    • javaScript
      • ES6
        • 变量声明
        • 模块化
        • 箭头函数
        • 你不知道的for...of
        • 新的数据结构Set和Map
        • JavaScript异步编程终极解决方案
        • ES6 Class 3a0c0a225a534984aabe9a943c5df975
      • JavaScript Error
      • JavaScript浅拷贝和深拷贝
      • JavaScript闭包
      • JavaScript最佳实践
      • JavaScript设计模式
      • async函数的polyfill
    • 深入理解JavaScript系列
      • JavaScript中的继承
      • JavaScript原始类型和引用类型
      • JavaScript浅拷贝和深拷贝
      • JavaScript手写系列
      • JavaScript之this
      • 词法环境和环境记录
      • JavaScript内存泄漏
      • 执行上下文
      • 从ECMAScript规范中学习this
    • TypeScript
      • TypeScript基础教程
      • Typescript高级操作
      • TypeScript工具类型
      • Typescript手写实现工具类型
      • Typescript总结(思维导图)
    • 浏览器原理
      • 页面渲染原理
      • 浏览器存储
      • JavaScript事件循环
      • 事件循环
      • 跨域
      • DOM事件流
      • 从输入url到页面渲染
      • 判断节点之间的关系及根据节点关系查找节点
      • history API
    • 跨端技术
      • Flutter
        • Flutter布局组件
    • 前端工程化
      • Babel插件开发指南
      • 循环依赖
      • pm2
    • React
      • React 状态管理
      • React组件通讯
      • Redux入门
      • Flux
      • React Hook(todo)
      • Effect
  • 服务器端
    • 计算机网络
      • 应用层
      • 运输层
      • 物理层
      • 数据链路层
      • HTTP缓存
      • HTTPS
      • 网络层
    • NodeJs
      • Node.js
      • nodejs最佳实践
      • 《深入浅出Nodejs》小结
      • mongoose填充(populate)
      • node事件循环
      • Node子进程
      • nestjs从零开始
      • nodejs流
      • Nodejs调试
      • Koa源码解析
    • 服务器
      • 操作系统
      • Linux
      • nginx常用指令
      • nginx常用配置
    • 数据库
      • Mysql常见语法
      • MongoDB Indexes索引
  • 前端安全与性能优化
    • 前端安全
      • 跨站脚本攻击(XSS)
      • 跨站点请求伪造(CSRF)
      • 点击劫持
      • 中间人攻击
      • 越权攻击与JWT
    • 前端性能优化
      • 前端监控系统
      • 前端性能优化总结与分析 7348bba0918645b1899006dc842a64c1
      • 衡量性能的核心指标 0dc15ef127cf4f4a9f1137c377420292
      • 图片懒加载
  • 杂项
    • 其他
      • Git
      • web component框架
      • 实现滚动框的懒加载
      • Stencil指南
    • CSS
      • 定位和层叠上下文
      • BFC
      • 盒模型
      • css选择器
      • css变量
由 GitBook 提供支持
在本页
  • TypeScript实用工具
  • 全局工具
  • 异步
  • Awaited
  • 对象属性转换
  • Partial
  • Required
  • Readonly
  • 根据条件构造对象类型
  • Record<Keys,Type>
  • Pick<Type, Keys>
  • Omit<Type, Keys>
  • 联合类型
  • Exclude<UnionType, ExcludedMenbers>
  • Extract<Type, Union>
  • NonNullable
  • 函数
  • Parameters
  • ReturnType
  • ConstructorParameters
  • InstanceType
  • ThisParameterType
  • OmitThisParameter
  • 字符串
在GitHub上编辑
  1. 前端技术
  2. TypeScript

TypeScript工具类型

TypeScript实用工具

全局工具

TypeScript提供了一些实用工具类型,这些工具类型全局可用。

异步

Awaited

Awaited用于获取Promise<Type>中的Type类型,这和async函数中的await很相似,只不过async函数中的await是取得Promise的值,而Awaited则是取得值的类型。

Type不仅可以是一个Promise类型,也可以是一个嵌套的Promise类型、字符串等基本类型,甚至还可以是一个联合类型。

type A = Awaited<Promise<string>>;
// A = string;
type A = Awaited<Promise<Promise<number>>>;
// A = string;
type A = Awaited<string>
// A = string;
type A = Awaited<boolean | Promise<number>>;
// A = boolean | number

示例

type GetListType = ()=>Promise<string>
const getList:GetListType = ()=> new Promise((resolve)=>{
    setTimeout(()=>{
        resolve('123')
    }, 1000)
})

async function fn(){
    // ReturnType接收函数,并返回该函数返回值的类型
    // 在这个例子里ReturnType<GetListType> = Promise<string>
    const res:Awaited<ReturnType<GetListType>> = await getList()
}

对象属性转换

Partial

Partial的作用是将Type中所有的属性都转换成可选的。

例如有些时候我们需要将接口中的所有属性都转换成可选的,这个时候没必要再重新写一遍,只需要用Partial类型转换一下即可。

interface Person {
    name: string;
    age: number
}

type ChangePersonType = Partial<Person>

function changePerson(arg: ChangePersonType){

}
changePerson({name: '李四'}) // ✔
changePerson({name: '李四',age: 18}) // ✔

Required

Required类型的作用刚好与Partial相反,它会将Type内的所有属性都转换成必填的。

type CreatePersonType = Required<ChangePersonType>

function createPerson(arg: CreatePersonType){

}
createPerson({name: '李四',age: 18}) // ✔
createPerson({name: '李四'})     // ✖

Readonly

顾名思义Readonly的作用是将Type中的所有属性都转换成只读的。

interface Person {
    name: string;
    age: number
}

const xiaoMing: Readonly<Person> = {name: '小明', age: 20}
xiaoMing.age += 1; // ✖

根据条件构造对象类型

Record<Keys,Type>

Record会构建一个包含所有键为Key,类型为Type的属性的对象类型,例如:

type PersonType = Record<'name' | 'age', string>

/*
类似于
interface PersonType  {
	name: string;
  age: string;
}
*/
const pserson:PersonType = {name: '小明', age: '21'}

Type也可以是对象类型:

interface CatInfo {
  age: number;
  breed: string;
}
 
type CatName = "miffy" | "boris" | "mordred";
 
const cats: Record<CatName, CatInfo> = {
  miffy: { age: 10, breed: "Persian" },
  boris: { age: 5, breed: "Maine Coon" },
  mordred: { age: 16, breed: "British Shorthair" },
};

Pick<Type, Keys>

Pick的作用是从Type中取得所有Keys属性来构建一个新的对象类型。

interface Boy {
    name: string;
    age: number;
    gender: "男"
}

type Person = Pick<Boy, 'name' | 'age'>
const xiaoMing:Person = {
    name: "小明",
    age: 18,
}

Omit<Type, Keys>

Omit和Pick类似,不过Omit是所有移除Key属性,并用剩余的属性来构建一个新的对象类型。

Pick的那个例子可以用Omit重写,效果相同。

interface Boy {
    name: string;
    age: number;
    gender: "男"
}
type Person = Omit<Boy, 'gender'>
const xiaoMing:Person = {
    name: "小明",
    age: 18,
}

联合类型

Exclude<UnionType, ExcludedMenbers>

Exclude会返回一个将UnionType联合类型中所有的ExcludedMenbers成员都移除的联合类型,例如:

type IsBoy = 1 | -1 | 0; // 是 | 否 | 不确定
const isBoy: Exclude<IsBoy, 0> = 0;  // ✖
const isBoy: Exclude<IsBoy, 0> = 1;  // ✔
// IsBoy = 1 | -1

Extract<Type, Union>

Extract会返回Type和Union的交集。

type IsBoy = 1 | -1 | 0
const isBoy: Extract<IsBoy, 1 | -1> = 1;
// IsBoy = 1 | -1

NonNullable

NonNullabe会将Type中的null和undefined类型移除,并返回一个新的类型。

type A = 1 | 0 | null | undefined;
const a: NonNullable<A> = null // ✖
const b: NonNullable<A> = undefined // ✖
const c: NonNullable<A> = 1 // ✔

函数

Parameters

返回包含函数所有参数的元组或者数组。

type Fn1 = (...args: number[])=>string
type Fn2 = (age: number, name: string) => string

type A = Parameters<Fn1>; // number[]
const a: A = [1]

type B = Parameters<Fn2>  // []
const b:B = [18,'小明'] 

ReturnType

返回函数返回值的类型。

type Fn1 = (...args: number[])=>string

type A = ReturnType<Fn1>; // string
const a: A = '1'

ConstructorParameters

从构造函数类型的参数类型构造元组或数组类型。它产生一个包含所有参数类型的元组类型(如果 Type 不是函数,则类型 never )。

type T0 = ConstructorParameters<ErrorConstructor>;
// type T0 = [message?: string | undefined]

class Fn{
    constructor(a:string, b?:number){}
}
type T1 = ConstructorParameters<typeof Fn>;
// type T1 = [a: string, b?: number | undefined]

InstanceType

构造一个由 Type 中构造函数的实例类型组成的类型。

class Fn{
    a: string;
    b?:number;
    constructor(a:string, b?:number){
        this.a = a;
        this.b = b
    }
}
type T1 = InstanceType<typeof Fn>;
const t1: T1 = new Fn('',1)  // ✔
const t2:T1 = new Error('')  // ✖

ThisParameterType

提取函数类型的 this参数的类型,如果函数类型没有 this参数,则为unknown

function toHex(this: Number, name: string) {
  return this.toString() + name;
}
console.log(toHex.call(10, ' name'))
// 10 name

type ToHexThisParameters = ThisParameterType<typeof toHex>
// type ToHexParameters = Number
const toHexThisParameters:ToHexThisParameters = Number(10)

OmitThisParameter

从 Type中移除 this参数。

如果 Type没有显式声明this,则直接返回 Type。否则,将从Type中创建一个不包含this的新函数类型。

function toHex(this: Number, name: string) {
  return this.toString() + name;
}

type ToHexThisParameters = OmitThisParameter<typeof toHex>
// type ToHexThisParameters = (name: string) => string
const toHexThisParameters:ToHexThisParameters = (name: string)=>name;

如果函数没有显示声明this类型:

function toHex(name: string) {
  return name;
}

type ToHexThisParameters = OmitThisParameter<typeof toHex>
// type ToHexThisParameters = (name: string) => string
const toHexThisParameters:ToHexThisParameters = (name: string)=>name;

字符串

Uppercase<StringType> : 将字符串中的每个字符转换为大写。

Lowercase<StringType> : 将字符串中的每个字符转换为小写。

Capitalize<StringType> : 将字符串中的第一个字符转换为等效的大写字母。

Uncapitalize<StringType> : 将字符串中的第一个字符转换为等效的小写字母。

const lowercase: Lowercase<string> = 'a'
const uppercase: Uppercase<string> = "A"
const capitalize: Capitalize<string> = 'Aa'
const uncapitalize:Uncapitalize<string> = 'aA'

const a: Lowercase<'A'> = 'a'
上一页Typescript高级操作下一页Typescript手写实现工具类型

最后更新于1年前