【问题标题】:Typescript, index one interface keys using another interfaceTypescript,使用另一个接口索引一个接口键
【发布时间】:2023-01-10 20:54:03
【问题描述】:

我有两个具有相同可选键但值不同的接口:

interface Obj1 {
 a?: string
 b?: string
 c?: string
}

interface Obj2 {
 a?: boolean
 b?: boolean
 c?: boolean
}

Obj1 用作函数参数,另一个 Obj2 是该函数的返回值。我希望返回类型仅标识 Obj1 上的给定键。因此,如果 Obj1 仅包含 ab,则 Obj2 也将仅包含 ab

我尝试了下面的方法,但是我得到了一个 ts 错误Type 'Property' cannot be used to index type 'ValueType'

type Obj1KeysWithObj2Values<KeyType extends Obj1, ValueType extends Obj2> = {
  [Property in keyof KeyType]: ValueType[Property]
}

【问题讨论】:

  • 你会用你试图使用它的函数的签名来更新你的问题吗?

标签: typescript


【解决方案1】:

问题是虽然知道 Obj2 将始终拥有 Obj1 的键的超集,TypeScript 不知道这一点,因此需要安心。 :-) 如果你想使用那些泛型,你可以通过使用条件类型来测试 ValueType 中是否也存在属性键来清除该错误:

type Obj1KeysWithObj2Values<KeyType extends Obj1, ValueType extends Obj2> = {
    [Property in keyof KeyType]: Property extends keyof ValueType ? ValueType[Property] : never;
// −−−−−−−−−−−−−−−−−−−−−−−−−−−−−^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
};

Playground example

【讨论】:

  • 也就是说,根据函数实际使用类型的方式,可能会有更简单的解决方案。如果您可以将函数的签名添加到问题中,我(或其他人)可能会提出更简单的建议。
猜你喜欢
  • 1970-01-01
  • 2018-12-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-06
  • 1970-01-01
  • 2016-10-11
相关资源
最近更新 更多