微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

标签元组的类型级别操作

如何解决标签元组的类型级别操作

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。