键入基于另一个属性值的键名

Type with key name based of another properties value

我有对话数据,其中一些键名包含其他键的值。是否可以在不使用 [key: string] 的情况下为此显式创建类型?

数据看起来像这样,在接下来的两个“新”键中使用两个 uid:

{
  uid0: "212122323",
  uid1: "797789667",
  new212122323: true,
  new797789667: false
}

我希望得到这样的类型(伪类型):

export type Conversation = {
    uid0: string,
    uid1: string,
    ["new"+this.uid0]: boolean,
    ["new"+this.uid1]: boolean,
}

如果数据来自任何外部来源,这是不可能的。像这样的类型只能静态工作,意味着在编译时。如果您在应用程序编译时不知道用户 ID,那么您就无法创建在这些 ID 上提供强类型的类型。

所以我认为你最接近的是:

type Conversation = {
  [key: `uid${number}`]: string
  [key: `new${number}`]: boolean
}

它是这样工作的:

const data: Conversation = {
  uid0: "212122323",
  uid1: "797789667",
  new212122323: true,
  new797789667: false
}

const testA = data.uid123 // string
const testB = data.new456 // boolean

并且应该检测有错误的无效道具:

const badData: Conversation = {
  uid0: "212122323",
  someProps: 'I dont belong here', // error
}

Playground