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>:从联合类型中排除指定成员
  • Extract<UnionType, ExtractedMembers>:从联合类型中提取指定成员
  • NonNullable<Type>:从 Type 中排除 nullundefined
  • Parameters<Type>:获取函数参数类型,并以元组形式返回
  • ReturnType<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, fields: Partial<Omit<Todo, 'id'>>) {
  return { ...todo, ...fields }
}

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 许可发布