首页 > 解决方案 > 能够从不相关的类型生成 TypeScript 元组?

问题描述

我发现了这个有趣的元组技巧,它基本上做了以下事情:

export type Lit = string | number | boolean | undefined | null | void | {};
export const tuple = <T extends Lit[]>(...args: T) => args;

const arr = tuple(1, 2, 3, 'hello', new Date, false)
// typeof arr is [1, 2, 3, 'hello', Date, false]

游乐场链接

但是,如果我更改 的定义Lit,它仍然有效:

export type Lit = symbol | {};
export const tuple = <T extends Lit[]>(...args: T) => args;

const arr = tuple(1, 2, 3, 'hello', new Date, false)
// typeof arr is [1, 2, 3, 'hello', Date, false]

游乐场链接

或者如果我设置Lit

export type Lit = '' | {};

它仍然有效!(游乐场链接

但是,如果我将 Lit 更改为其他内容,例如

export type Lit = undefined | {};

然后我得到一个不同的结果类型arr

const arr = tuple(1, 2, 3, 'hello', new Date, false)
// typeof arr is [number, number, number, string, Date, boolean]

游乐场链接

这里发生了什么?

标签: typescript

解决方案


推荐阅读