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'.
constyou will find that it works. That's because the type is now the literal"text"and you can access the propertytext. For arbitrary strings, you either have to check and cast, or use an index signature, but the former is probably preferable for this case.