Home > Software engineering >  String manipulation required before using it as an object key
String manipulation required before using it as an object key

Time:08-08

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:

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?

CodePudding user response:

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

  • Related