简体   繁体   English

使用 Typescript 中的括号表示法从 object 更新嵌套属性

[英]Updating nested properties from an object with bracket notation in Typescript

So say I've got this interface and object with nested properties:所以说我有这个接口和带有嵌套属性的 object:

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:我有一个字符串可以识别 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但这些语句给了我错误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.似乎obj[prop]未被识别为有效。 Something I'm doing wrong here?我在这里做错了什么?

The problem is that with obj['a.a2'] the Javascript expects obj to have been defined like this:问题在于,对于obj['a.a2'] ,Javascript 期望obj的定义如下:

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.但是,在您的情况下, a2a的子级,因此首先您需要访问a然后访问a2 ,这就是为什么在您的情况下obj['a']['a2']起作用的原因。 However if you still insist to use a.a2 then you can use Lodash library which understands that key.但是,如果您仍然坚持使用a.a2 ,那么您可以使用能够理解该密钥的 Lodash 库。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM