我发现了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]
但是,如果我更改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 = '' | {};
它仍然有效! (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]
这是怎么回事?