【问题标题】:Type level operations for labelled tuple标记元组的类型级操作
【发布时间】:2020-10-04 20:04:06
【问题描述】:

我想用标记的元组做类似于下面的事情,并想知道这在 TS4 中是否可行

type stringProperties<T extends {}> = {[k in keyof T]: string}

这意味着我可以创建一个类型 [foo: string, bar: string, baz:string]来自[foo: boolean, bar: number, baz: any]

目前我缺少一般捕获标签的方法(它不存在于 keyof 中)并且不确定如何将另一个标签:类型对添加到现有的元组类型。

我知道下面的技术可以添加到未标记的元组,但在这种情况下,标签将设置为 first

export type Prepend<E, T extends any[]> =
    ((first: E, ...args: T) => any) extends ((...args: infer U) => any)
    ? U
    : never

【问题讨论】:

  • 您是否尝试创建一种类型,将类型的属性转换为元组类型,以便每个元组元素对应一个属性并由该属性的键标记,还是您想要相反?

标签: typescript type-level-computation typescript4.0


【解决方案1】:

您可以使用mapped tuple types 来更改元素类型。他们的labels 被保留:

type T1 = stringProperties<[foo: boolean, bar: number, 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, bar: number, baz: any]
type T3 = Append<[customLabel: string], A> 
// [foo: boolean, bar: number, baz: any, customLabel: string]
type T4 = Prepend<[customLabel: string], stringProperties<A>> // or mix it up
// [customLabel: string, foo: string, bar: string, baz: string]
...后来使用类型作为函数参数:
function foo(...args: T4) {}
// function foo(customLabel: string, foo: string, bar: string, baz: string): void

Playground

【讨论】:

    【解决方案2】:

    适用于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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-21
      • 1970-01-01
      • 2023-03-18
      • 2017-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多