0

So say I've got this interface and object with nested properties:

interface Iobj {
  a: { a2:string };
  b: string;
}

const obj: Iobj = {
  a:{
    a2: "hello"
  }
  b: "world"
};

And I've got a strings that identify properties in obj:

const prop = "a.a2"
// or
const prop = "b"

I'm trying to update obj with bracket notation but these statements give me the error Type 'string' is not assignable to type 'never'.

obj[prop] = "newString";
obj[prop as keyof Iobj] = "newString";

Seems like obj[prop] isn't being recognized as valid. Something I'm doing wrong here?

2
  • 2
    obj["a.a2"] won't work even in vanilla JS; you would have to use something like lodash.get. Commented May 19, 2021 at 16:09
  • Valid prop (e.g. "b") works fine typescriptlang.org/play?#code/… Commented May 19, 2021 at 16:14

1 Answer 1

1

The problem is that with obj['a.a2'] the Javascript expects obj to have been defined like this:

obj = {
  "a.a2": "hello"
}

However in you case a2 is child of a so first you need to access a then access a2, That's why in your case obj['a']['a2'] works instead. However if you still insist to use a.a2 then you can use Lodash library which understands that key.

https://lodash.com/docs/4.17.15#set

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.