0

Well I have an object which behaves like a dictionary - except for having a few static fields (that are of different type).

ID:

{
    id: number,
    key: string,
    en_gb: string,
    de_de: string,
    //...any more locale
}

So I tried to use a combination of both a dictionary as well as static object:

{
    id: number,
    key: string,
    [locale: string]: string
}

However now I get that property of type "number" is not assignable to string index type "string".

How would I handle such an object in typescript, what is the proper typing when I am given data in this format?

paul23
  • 8,799
  • 12
  • 66
  • 149
  • This isn't really supported [see this Github issue](https://github.com/microsoft/TypeScript/issues/17867). For now, the only way you can get this to work is to using a union: `[locale: string]: string | number`. But that will allow `id` to be a string which isn't what you want. – Get Off My Lawn Jan 13 '21 at 20:38

1 Answers1

0

I hope it will work for you:

/**
 * First approach
 * If you know all locales
 */
type Locales = 'en_gb' | 'de_de' | 'ua_ua'

type Data = {
  id: number,
  key: string,
}

type Resp = {
  [P in Locales]: string
} & Data;

type Result = Resp

/**
 * First and the half approach
 */

{
  type Locales = 'en' | 'de' | 'ua'

  type EdgeCases<T extends string> = T extends 'en' ? 'gb' : T

  type Result = {
    [P in Locales as `${P}_${EdgeCases<P>}`]: P
  } & Data
}

/**
 * Second approach
 * You don't know all possible locales
 */

{

  type Locales = {
    [locale: string]: string
  } & Data

  type Result = Locales['id'] // number
  type Result2 = Locales['key'] //  string
  type Result3 = Locales['any locale'] //string
}