我试图通过使用keyof TestInterface类型的动态键访问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相关问答推荐

我可以获取所有包含@的超链接,然后在新选项卡中打开它们吗?

功能和普通对象之间的原型污染

从外部访问组件变量-Vueejs

创建1:1比例元素,以另一个元素为中心

无法将nPM simplex-noise包导入在JS项目中工作

JavaScript文本区域阻止KeyDown/KeyUp事件本身上的Alt GR +键组合

为什么getRecord()会因为与_logger相关的错误而失败?(使用Hedera SDK)

使用JavaScript在ionic Web应用程序中更新.pane和.view的背景 colored颜色

拖放仅通过 Select 上传

如何在Obsidian dataview中创建进度条

在react JS中映射数组对象的嵌套数据

JS—删除对象数组中对象的子对象

如何从HTML对话框中检索单选项组的值?

如何在.NET Core中将chtml文件链接到Java脚本文件?

当我try 将值更改为True时,按钮不会锁定

为什么可选参数的顺序会导致问题?

我想将Sitecore搜索面过滤器从多个转换为单个

Google脚本数组映射函数横向输出

使用jQuery find()获取元素的属性

用另一个带有类名的div包装元素