Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

String manipulation required before using it as an object key

I have an object:

const myObject = {
    aaa: 'a value',
    bbb: 'b value',
    ccc: 'c value',
}

At runtime, I may receive strings like aaa 1, aaa 2 and bbb 3 etc, which will go through certain string manipulation before being used as a key into the object. In code terms:

const input = 'aaa 1'
const correctKey = inuput.substring(0, input.indexOf(' ')) // so now correctKey is 'aaa'
console.log(myObject[correctKey]) // my goal is to have 'a value' returned

Now the compiler error:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Element implicitly has an ‘any’ type because expression of type ‘string’ can’t be used to index type ‘{ aaa: string; bbb: string; ccc: string; }’.
No index signature with a parameter of type ‘string’ was found on type ‘{ aaa: string; bbb: string; ccc: string; }’

How should I go about it?

>Solution :

Since input is assigned at runtime, you can only hint the compiler that correctKey is one of the keys of myObject:

const correctKey = input.substring(0, input.indexOf(' ')) as keyof typeof myObject;

Demo

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading