Skip to content

工具类型

类型说明
Awaited<Type>获取 Promise 中的结果类型
Partial<Type>将 Type 中的所有属性设置为 可选属性,返回一个新的类型。
Required<Type>将 Type 中的所有属性设置为 必选属性,返回一个新的类型。
Readonly<Type>将 Type 中的所有属性设置为 只读属性,返回一个新的类型。
Record<Keys, Type>新建一个由 Keys 指定的属性和 Type 指定的值组成的对象类型。
Pick<Type,Keys> 从 Type 中选择一个或多个属性,并返回一个新的类型。
Omit<Type,Keys> 从 Type 中删除一个或多个属性,并返回一个新的类型。
Exclude<UnionType, ExcludedMembers> 从 UnionType 中排除 ExcludedMembers 中的所有类型,并返回一个新的类型。
Extract<UnionType, ExtractedMembers>从 UnionType 中提取 ExtractedMembers 中的所有类型,并返回一个新的类型。
NonNullable<Type>从 Type 中排除 null 和 undefined 类型,并返回一个新的类型。
Parameters<Type>获取函数类型 Type 的参数类型,以元组类型返回。
ReturnType<Type>获取函数类型 Type 的返回值类型。

示例

ts
function get(url: string) {
  return fetch(url).then(resp => resp.json()) as Promise<{ ok: boolean }>
}

type GetFunc = typeof get
type Params = Parameters<GetFunc>
type Return = ReturnType<GetFunc>
type Data = Awaited<Return>

////////////////////////////////////

type Options = {
  method?: 'GET' | 'POST'
  url: string
  data?: any
}

// let defaultOptions: Pick<Options, 'method'> = {
//   method: undefined
// }
let defaultOptions: Required<Pick<Options, 'method'>> = {
  method: 'GET',
}
let defaultOptions2: Required<Omit<Options, 'url' | 'data'>> = {
  method: 'GET',
}

function mergeOptions(options: Readonly<Options>) {
  // options.method = 'POST'

  // return { ...defaultOptions, ...options }
  return { ...defaultOptions2, ...options }
}

////////////////////////////////////

// {
//   zh: {
//     // ...
//   },
//   en: {
//     // ...
//   },
//   // ...
// }

type language = 'zh' | 'en' | 'jp'
type Trans = { you: string; and: string; me: string }

type I18n = Record<language, Trans>

////////////////////////////////////

interface Todo {
  id: number
  title: string
  desc: string
}

function updateTodo(todo: Todo, fileds: Partial<Omit<Todo, 'id'>>) {
  return { ...todo, ...fileds }
}

updateTodo({ id: 1, title: 'aaa', desc: 'aaa' }, { title: 'ccc' })

////////////////////////////////////

type Topics = 'html' | 'css' | 'js' | 'ts' | 'java' | 'go'
type FeTopics = Exclude<Topics, 'java' | 'go' | 'c#'>
type BeTopics = Extract<Topics, 'java' | 'go' | 'c#'>

////////////////////////////////////

type T0 = string | number | undefined | null
type T00 = NonNullable<T0>

参阅

基于 MIT 许可发布