标签元组的类型级别操作

问题描述

我想对带有标记元组执行以下类似操作,并想知道它在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>

enter image description here

,

您可以使用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

Playground

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...