好用但不常用的typescript技巧

49 阅读1分钟

前言

在项目开发中偶尔会遇到一些场景,需要使用不太常用的typescript方法,又由于不太常用,所以往往会忘记怎么使用,因此在这里做个记录,方便以后查看。

场景

利用数组生成联合类型

const a = ['萝卜', '苹果'] as const
type A = typeof a[number] // type A = '萝卜' | '苹果'

将数组类型转为非数组类型

// 普通数组类型
type A = {a: string}[]
type B = A[number] // type B = {a: string}

// 对象类型中的数组类型
interface A {
    B: { a: string }[]
}
type C = A['B'][number] // type C = {a: string}

// 对象中的可选数组类型
interface A {
    B?: { a: string }[]
}
type C = NonNullable<A['B']>[number] // type C = {a: string}

修改对象类型

interface A {
    a: string;
    b?: number;
}
// 删除某项
type B = Omit<A, 'a'> // type B = { b?: number }

// 使所有项变成可选
type C = Partial<A> // type C = {a?: string; b?: number}

// 使所有项变成必选
type D = Required<A> // type D = {a: string; b: number}