vue3
TypeScript
1. Partial
Partial<
type> 可以把$\color{#FF0000}{type}$中所有属性变为可选属性
interface Todo {
title: string
description: string
}
function updateTodo(todo: Todo, fieldsToUpdate: Partial<Todo>) {
return { ...todo, ...fieldsToUpdate }
}
const todo1 = { title: 'organize desk', description: 'clear clutter' }
const todo2 = updateTodo(todo1, { description: 'throw out trash' })
2.Record
Record<Keys, Type> 构造一个具有一组$\color{#FF0000}{ Keys }$类型的属性$\color{#FF0000}{Type}$的类型 (属性名为 keys 的类型为 type 的类型)
interface CatInfo {
age: number
breed: string
}
type CatName = 'miffy' | 'boris'
const cats: Record<CatName, CatInfo> = {
miffy: { age: 10, breed: 'Persian' },
boris: { age: 5, breed: 'Maine Coon' },
}
3.Pick
Pick<Type, Keys> 从 Type 中选择一组其键在并集 Keys 中的属性(在 type 中选择 keys 中的某几个属性组成新的类型)
interface Todo {
name: string
description: string
completed: boolean
}
type TodoPreview = Pick<Todo, 'name' | 'load'>
const todo: TodoPreview = {
name: 'Clean room',
load: false,
}
4.Exclude
Exclude<UnionType, ExcludedMembers> , 从
UnionType中排除掉ExcludedMembers的类型(求补集)
type T0 = Exclude<'a' | 'b' | 'c', 'a'> // 👉 type T0 = "b" | "c"
type T1 = Exclude<'a' | 'b' | 'c', 'a' | 'b'> // 👉 type T1 = "c"
type T2 = Exclude<string | number | (() => void), Function>
// 👉 type T2 = string | number
5.Extract
Extract<Type, Union>, 通过从 $\color{#FF0000}{Type}$ 中提取所有可分配给 Union 的联合成员来构造一个类型(求交集)。
type T0 = Extract<'a' | 'b' | 'c', 'a' | 'f'> // type T0 = "a"
type T1 = Extract<string | number | (() => void), Function> // type T1 = () => void
6.NonNullable
NonNullable<type,> ,排除$\color{#FF0000}{type}$中的 undefined 和 null 类型
type T0 = NonNullable<string | number | undefined> // type T0 = string | number
type T1 = NonNullable<string[] | null | undefined> // type T1 = string[]
7.Omit
Omit<Type, Keys> ,构造一个不包含$\color{#FF0000}{Keys}$ 的新类型
interface Todo {
name: string
completed: boolean
createdAt: number
}
type TodoPreview = Omit<Todo, 'name'>
const todo: TodoPreview = {
completed: false,
createdAt: 1615544252770,
}
8.ReturnType
ReturnType<Type,>,构造一个由函数 Type 的返回类型组成的类型。
declare function f1(): { a: number; b: string }
type T0 = ReturnType<() => string> // type T0 = string
type T1 = ReturnType<(s: string) => void> // type T1 = void
type T2 = ReturnType<<T>() => T> // type T2 = unknown
type T3 = ReturnType<<T extends U, U extends number[]>() => T> // type T3 = number[]
type T4 = ReturnType<typeof f1> // type T4 = { // a: number; // b: string; // }
type T5 = ReturnType<any> // type T5 = any
type T6 = ReturnType<never> // type T6 = never