Home > Software design >  How to get dictionary value by key
How to get dictionary value by key

Time:12-06

This is my dict:

export const roles = {
  "key1": "value1",
  "key2": "value2",
  "key3": "value3"
};

I want to get the value by key like so:

let x = "key1"; 
let y = roles[x]

And I'm getting the error

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ key1: string; key2: string; key3: string; }'. No index signature with a parameter of type 'string' was found on type '{ key1: string; key2: string; key3: string; }'.ts(7053)

How do I do it right?

CodePudding user response:

error message "Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ key1: string; key2: string; key3: string; }'. No index signature with a parameter of type 'string' was found on type '{ key1: string; key2: string; key3: string; }'."

// Provide a type for the x variable
let x: keyof typeof roles = "key1";
let y = roles[x];

CodePudding user response:

Was able to figure this our with an interface like so:

interface LoosObject {
[key: string]: any
}

export const roles: LoosObject = {
  "key1": "value1",
  "key2": "value2",
  "key3": "value3",
};

CodePudding user response:

It looks like you're trying to access an object property by using a variable.
In TypeScript, this is not allowed by default because it can lead to unexpected behavior.
You can fix this error by adding an index signature to your object, like this:

export const roles = {
  "key1": "value1",
  "key2": "value2",
  "key3": "value3",
  [x: string]: any // add this line
};

let x = "key1"; 
let y = roles[x] // this should work now
  • Related