Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

152
Visualizações
Typescript access and assign object property by dynamic key

I am trying to assign a value from an object of type TestInterface to another object of type TestInterface by accessing it with a dynamic key of type keyof TestInterface. However typescript seems to forget that this key is the same on both instances and therefore throws an error.

Since this sentence is hard to read, here is an example:

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']

The tricky part is that testKey in the assignment of myTestKey should actually be any value of type string.

I was wondering whether this is a bug or how I can do this properly? Here is the Link to the Typescript Playground.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

I managed to find a not-too-dirty workaround that works for my use case. See example below:

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

Note: myObj is now let instead of const

Typescript Playground

about 4 years ago · Juan Pablo Isaza Relatório

0

You need to add type as -

const myTestKey: keyof TestInterface = 'testKey';

Playground

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda