【问题标题】:Can I add a prefix or suffix to the keys of a TypeScript interface/type which is programmatically generated?我可以为以编​​程方式生成的 TypeScript 接口/类型的键添加前缀或后缀吗?
【发布时间】:2021-01-20 15:15:17
【问题描述】:

我想知道,是否可以为使用字符串数组作为键的 TypeScript 类型添加前缀或后缀。

type First = {
  one: string
  two: string
}

type Second = keyof First 

type Third = {
  [S in Second]: any
}

使用这种方法,Third 接受任何类型的属性onetwo。这太棒了,因为我只需要更改第一种类型就可以更新其他类型。

现在我想要第四种类型,它与Third 完全相同,但我想为键添加前缀。比如美元符号什么的。

想要的结果:

type Fourth = {
  $one: any
  $two: any
}

我可以对其进行硬编码,但如果第一个类型已更改,我将不得不调整第四个类型。

谢谢。

【问题讨论】:

    标签: typescript typing


    【解决方案1】:

    TS 4.1 has support for easy key remapping 使用模板文字类型:

    type First = {
      one: string
      two: string
    }
    
    type Fourth = {
        [K in keyof First as `$${K}`]: any
    }
    

    如果您想使用与每个键关联的原始类型而不是 any(如果您使用 TS,则应该尽可能避免使用 any,毕竟!),替换

    : any
    

    : First[K]
    

    【讨论】:

    • 谢谢!刚刚更新到 4.1 版。也感谢第二个提示。这很有帮助。 any 仅用于示例。在我的代码中,我需要引用一个新类型,但绝对值得知道如何映射原始类型。 ?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-17
    • 2010-10-27
    • 1970-01-01
    • 1970-01-01
    • 2021-06-22
    • 1970-01-01
    相关资源
    最近更新 更多