0

How do I access a property on an object type with it's key name in Typescript?

type MyType = {
  text: string;
}

var item: MyType = {
  text: "Hello World!"
}

// How do I do this?
let keyName = "text";
let key = keyName;
item[key] = "New Value";

I get this error.

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'MyType'. No index signature with a parameter of type 'string' was found on type 'MyType'.

1
  • If you declare it with const you will find that it works. That's because the type is now the literal "text" and you can access the property text. For arbitrary strings, you either have to check and cast, or use an index signature, but the former is probably preferable for this case. Commented Mar 17, 2022 at 18:03

1 Answer 1

2

The type of key is generalised as string if you don't explicitly specify a type for it:

let key = "text" // let key: string

You can constrain values for key to only keys of MyType, after which it is okay to use it as access key for item:

let key: keyof MyType = "text" // let key: string

See a working example.

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

1 Comment

Thank you! I made one small edit to my example. I have a function returning the string for the key name. I'm still not sure how to resolve that as I still get an error if I try do this. let keyName = "text"; let key: keyof MyType = keyName;

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.