1

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,
}
2
  • Need a bit more info here. Because your data there, as a constant, is already implicitly that type Add some info on how you get this data and expect to strongly type it Commented Mar 1, 2022 at 23:00
  • @AlexWayne data is from a database ~ I'm new to TypeScript and I found it very satisfyingly to have exact types for every object from the database. In this case I think I'll just have to be a bit looser on the type definition and use [key: string]: string | boolean along with uid0 and uid1. Commented Mar 1, 2022 at 23:40

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Great solution thank you, I never though about combining a string and number in the key.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.