问题描述
我想对带有标记的元组执行以下类似操作,并想知道它在TS4中是否可行
type stringProperties<T extends {}> = {[k in keyof T]: string}
这意味着我可以创建一个类型
[foo: string,bar: string,baz:string]
中的[foo: boolean,bar: number,baz: any]
此刻,我缺少通用捕获标签的方法(keyof中不存在该标签),并且不确定如何向现有元组类型添加另一个label:type对。
我知道下面的技术可以在未标记的元组之前添加,但是在这种情况下,标签将设置为first
。
export type Prepend<E,T extends any[]> =
((first: E,...args: T) => any) extends ((...args: infer U) => any)
? U
: never
解决方法
在latest version in the playground(4.1.0-dev.20201003)上工作:
type stringProperties<T extends {}> = {[k in keyof T]: string}
type A = [foo: boolean,bar: number,baz: any]
type B = stringProperties<A>
,
您可以使用mapped tuple types来更改元素类型。他们的labels被保留:
type T1 = stringProperties<[foo: boolean,baz: any]>
// [foo: string,bar: string,baz: string]
在cannot directly extract函数参数名称的同时,TS 4.0 variadic tuple types仍可以添加新的标签元素:
type Prepend<E extends [unknown],A extends any[]> = [...E,...A]
type Append<E extends [unknown],A extends any[]> = [...A,...E]
// ... extend to your needs
type T2 = Prepend<[customLabel: string],A>
// [customLabel: string,foo: boolean,baz: any]
type T3 = Append<[customLabel: string],A>
// [foo: boolean,baz: any,customLabel: string]
type T4 = Prepend<[customLabel: string],stringProperties<A>> // or mix it up
// [customLabel: string,foo: string,baz: string]
...然后将类型用作函数参数:
function foo(...args: T4) {}
// function foo(customLabel: string,baz: string): void