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

98
Visualizações
reference to partial object in typescript?

I have an object and it's typed

interface formDataType {
  tesla: {
    made: string
  },
  ford: {
    made: string
  }
}
const formData: formDataType = {
    "tesla": {
      "made":"2021"
    },
    "ford": {
      "made": "2022"
    }
  };

then I've a function where its argument is one of [string]:{made: string}, how can I use back formDataType? is there something like objectOf formDataType?

demo https://codesandbox.io/s/react-typescript-forked-cwv9p

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

0

You can create a type to use in your FormDataType, then reuse that type in your function:

TS Playground

type VehicleDetails = { made: string };

type FormDataType = {
  ford: VehicleDetails;
  tesla: VehicleDetails;
};

// The following is the same type, written using the Record utility:
// type FormDataType = Record<'ford' | 'tesla', VehicleDetails>;

const formData: FormDataType = {
  tesla: {made: '2021'},
  ford: {made: '2022'},
};

function doSomethingWithVehicleDetails (details: VehicleDetails) {
  // console.log(details);
}


Update in response to your comment:

You can also derive a union of all the types of the values of the keys in your FormData type (and if they're all the same type, the union will effectively be that one type):

TS Playground

type FormDataType = {
  ford: { made: string };
  tesla: { made: string };
};

type VehicleDetails = FormDataType[keyof FormDataType];

function doSomethingWithVehicleDetails (details: VehicleDetails) {
  // console.log(details);
}

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