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

141
Visualizações
type of dynamically accessed property in typescript

I have a function I want to reuse that is applicable on multiple properties of a custom type. Something like this:

interface MyType {
  prop1: string;
  prop2: number;
}
type MyTypeKey = keyof MyType;

const testValue = (
  obj: MyType,
  property: MyTypeKey,
  value: any, // <-- what type should go here?
) => {
  if (obj[property] === value) {
    console.log("do something");
  }
}

testValue({prop1: "a", prop2: 1}, "prop1", "okay"); // should be okay
testValue({prop1: "a", prop2: 1}, "prop2", "oops"); // should be error

But I don't know how to do this since I don't know the type of the property value. How can I solve this?

(I am new to javascript/typescript, so forgive me for small typos and constructions and bad practices)

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

0

Use a generic argument to indicate the key. From that key you can look it up on MyType to get the associated value's type, and require that the value argument to the generic function be that type.

interface MyType {
    prop1: string;
    prop2: number;
}

const testValue = <K extends keyof MyType>(
    obj: MyType,
    property: K,
    value: MyType[K],
) => {
    if (obj[property] === value) {
        // ...
    }
}

declare const obj: MyType;
// OK
testValue(obj, 'prop2', 3);
// Not OK
testValue(obj, 'prop2', 'a');

For a more flexible function that can validate any sort of object, without hard-coding MyType into it, make another generic type for the object.

const testValue = <O extends object, K extends keyof O>(
    obj: O,
    property: K,
    value: O[K],
) => {
    if (obj[property] === value) {
        // ...
    }
}
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