我试图通过使用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的链接.