Home > Mobile >  How to type chained calls to a Typescript object
How to type chained calls to a Typescript object

Time:09-29

I need to create a translation system where the elements are in a Typescript object like this:

const fr: AppMessages = {
  builder: {
    actionButtons: {
      preview: 'Visualisation',
      ...
    },
  },
};

So I typed the object with this type:

interface AppMessages extends Record<string, string | AppMessages> {}

But when I want to read a subkey :

const test: string = fr.builder.actionsButton.preview;

Typescript shows me this error: TS2339: Property 'actionsButton' does not exist on type 'string | AppMessages'.   Property 'actionsButton' does not exist on type 'string'.

Is it possible to make it tell me that the intermediate key returns a specific type, in this case that builder returns AppMessages and not string, or is it my type that I need to write differently?

Thx for your responses!

CodePudding user response:

If your entire messages object is statically declared, you can just use a const assertion:

const fr  = {
  builder: {
    actionButtons: {
      preview: 'Visualisation'
    },
  },
} as const;

const t = fr.builder.actionButtons.preview;
  • Related