【问题标题】:Replace types on some keys in a Typescript type替换 Typescript 类型中某些键上的类型
【发布时间】:2020-10-09 15:43:36
【问题描述】:

在下面的代码中,我试图通过循环键并仅替换与条件匹配的键,从现有类型创建一个新类型。

我在这里也使用联合类型。

class A {}

class B {
    constructor(public a: A, public n: number, public aa: A[]) {}
}

type X = A | B

type ReplaceKeyTypes<Type extends X, NewKeyType> = {
  [Key in keyof Type]: Key extends X ? NewKeyType : Type[Key]
}

const a: A = new A()
const b: B = new B(a, 1, [a, a])

const c: ReplaceKeyTypes<B, string> = {
    a: 'test',
    n: 2,
    aa: ['xyz']
}

这在最后几行代码中给了我以下错误:

  • 类型“数字”不能分配给类型“字符串”。
  • 类型“string[]”不可分配给类型“string”。

我的问题是:

  1. 为什么c.n变成一个字符串,而原来的key类型是一个不满足“Key extends X”的数字?
  2. 如何将更改应用于联合类型数组的键?在此示例中,c.aa 应从 X[] 更改为 string[]

【问题讨论】:

  • 我明天可以仔细研究一下,但是“Key extends X”实际上没有意义,因为您将密钥本身与接口的联合进行比较。您尝试替换的实际情况是什么?
  • 谢谢琳达!我设法找到了我的错误并在下面发布了一个错误,但如果您想查看它并让我知道是否有任何改进,我会很高兴。再次感谢!

标签: typescript


【解决方案1】:

似乎在执行Key in keyof Type 时,您会得到文字键,即命名键的字符串。我忘记使用Type[Key] 获取密钥的value 类型。为了修复和支持数组案例,我想出了以下方法:

type ReplaceKeyTypes<Type extends X, NewKeyType> = {
  [Key in keyof Type]: Type[Key] extends X[]
    ? NewKeyType[]
    : Type[Key] extends X
    ? NewKeyType
    : Type[Key]
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-06
    • 1970-01-01
    • 2023-01-16
    • 1970-01-01
    • 1970-01-01
    • 2021-08-06
    • 2017-12-28
    相关资源
    最近更新 更多