Estoy tratando de asignar un valor de un objeto de tipo TestInterface a otro objeto de tipo TestInterface accediendo a él con una clave dinámica de tipo keyof TestInterface . Sin embargo, mecanografiado parece olvidar que esta clave es la misma en ambas instancias y, por lo tanto, arroja un error.
Como esta oración es difícil de leer, aquí hay un ejemplo:
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'] La parte complicada es que testKey en la asignación de myTestKey debería ser cualquier valor de tipo cadena.
Me preguntaba si esto es un error o cómo puedo hacerlo correctamente. Aquí está el enlace al patio de juegos mecanografiado .