Home > database >  Type with key name based of another properties value
Type with key name based of another properties value

Time:03-03

I have conversation data where some key names contain values of other keys. Is it possible to explicitly create a type for this without using [key: string]?

The data looks like this, using the two uids in the next two "new" keys:

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

I'm hoping to get a type like this (pseudotype):

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

CodePudding user response:

This is not possible if the data comes from any external source. Types like this only work statically, meaning at compile time. If you don't know the user ids when the app compiles, then you can't make a type that provides strong typing on those ids.

So I think the closest you're going to get is something like:

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

Which works like so:

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

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

And should detect invalid props with errors:

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

Playground

  • Related