Home > Mobile >  How to access custom type value in Typescript
How to access custom type value in Typescript

Time:11-14

I'm new in typescript and I couldn't find the answer so I would like to ask how can I access to custom type value?

Let's say I have my custom type like this

type Notes = {
  5: number;
  10: number;
  20: number;
}

and I create instance like this

const availableNotes: Notes = {
  5: 10,
  10: 20,
  20: 40,
};

I tried to access the values of availableNotes like this

const noteTypes: string[] = Object.keys(availableNotes);

for(let i = 0; i < noteTypes.length; i  ) {
  const value = availableNotes[noteTypes[i]] 
  ... // Some logic
}

And this is an error

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ '5': number; '10': number; '20': number; }'.
  No index signature with a parameter of type 'string' was found on type '{ '5': number; '10': number; '20': number; }'

Appreciate your help!

CodePudding user response:

So, I've spent some time trying different soultions and I've found a quite ugly one, but it works.

The whole magic is to cast type of the key to keyof Notes. At first, we need to cast noteTypes[i] to unknown, because TypeScript complies about casting string (noteTypes[i]) to keyof Notes directly.

Working example (tested on TypeScript v4.4.4 and v3.3.3):

type Notes = {
  5: number;
  10: number;
  20: number;
}

const availableNotes: Notes = {
  5: 10,
  10: 20,
  20: 40,
};

const noteTypes = Object.keys(availableNotes);

for(let i = 0; i < noteTypes.length; i  ) {
  const key = noteTypes[i] as unknown as (keyof Notes);
  const value = availableNotes[key];
  console.log(value);
}
  • Related