gpt4 book ai didi

javascript - typescript 通过动态键访问和分配对象属性

转载 作者:行者123 更新时间:2023-12-05 03:25:01 24 4
gpt4 key购买 nike

我试图通过使用 keyof TestInterface 类型的动态键访问它,将类型为 TestInterface 的对象的值分配给类型为 TestInterface 的另一个对象。然而 typescript 似乎忘记了这个键在两个实例上是相同的,因此会抛出错误。

由于这句话很难读,下面是一个例子:

interface TestInterface {
testKey?: NestesOptInterface;
optKey?: string;
}

interface NestesOptInterface {
key1?: string;
key2?: string
}

const myObj : TestInterface= {

}

const myObj2 : TestInterface = {
testKey: {
key1: "test",
}
}

const attributes : string[] = ['testKey', 'optKey']

const myTestKey: keyof TestInterface = attributes[0] as keyof TestInterface

/**Type 'string | NestesOptInterface | undefined' is not assignable to type '(NestesOptInterface & string) | undefined'.
* Type 'NestesOptInterface' is not assignable to type 'NestesOptInterface & string'.
* Type 'NestesOptInterface' is not assignable to type 'string'.(2322)**/
myObj[myTestKey] = myObj2[myTestKey]

//does work (obviously)
myObj['testKey'] = myObj2['testKey']

棘手的部分是 myTestKey 赋值中的 testKey 实际上应该是字符串类型的任何值。

我想知道这是否是一个错误,或者我该如何正确地做到这一点?这是 Typescript Playground 的链接.

最佳答案

我设法找到了一个不太脏的解决方法,适用于我的用例。请参见下面的示例:

//solution
myObj = {
...myObj,
[myTestKey]: myObj2[myTestKey]
}

注意:myObj 现在是 let 而不是 const

Typescript Playground

关于javascript - typescript 通过动态键访问和分配对象属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72140074/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com