能够从无关类型生成TypeScript元组?

时间:2018-12-01 07:50:46

标签: typescript

我发现了this个有趣的元组技巧,基本上可以完成以下任务:

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]

playground link

但是,如果我更改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]

playground link

或者如果我将Lit设置为

export type Lit = '' | {};

它仍然有效! (playground link

但是如果我将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]

playground link

这是怎么回事?

0 个答案:

没有答案