打字稿访问并通过动态键分配对象属性

Typescript access and assign object property by dynamic key

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

由于这句话很难读,举个例子:

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 实际上应该是字符串类型的任何值。

我想知道这是否是一个错误,或者我该如何正确执行此操作?这是 Link 到 Typescript Playground.

您需要将类型添加为 -

const myTestKey: keyof TestInterface = 'testKey';

Playground

我设法找到了适用于我的用例的 not-too-dirty 解决方法。请参见下面的示例:

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

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

Typescript Playground