是否有一种实用程序类型可以将元组类型中的所有元素转换为接受TypeScript中的"undefined&quo



是否有一种实用程序类型可以将元组类型中的所有元素转换为接受undefined

输入

type InputType = [string, number]

预期输出

type OptionalInputType = [string|undefined, number|undefined]

您可以在数组和元组上使用映射类型来生成新的数组和元组。这意味着你可以定义这个:

type MapUnionWithUndefined<T> = { [K in keyof T]: T[K] | undefined };

它会成为你想要的类型。

type OptionalInputType = MapUnionWithUndefined<InputType>;
// type OptionalInputType = [string | undefined, number | undefined]

注意,这些并不是真正的";可选";,因为它们仍然要求元组的长度为2:

const okay: OptionalInputType = [undefined, undefined]; // okay
const boo: OptionalInputType = []; // error!

如果您想接受长度为0、1或2的元组,您只需使用内置的Partial<T>实用程序类型:

type TrulyOptionalInputType = Partial<InputType>;
// type TrulyOptionalInputType = [(string | undefined)?, (number | undefined)?]
const nowOkay: TrulyOptionalInputType = []; // okay

游乐场链接到代码

相关内容

最新更新