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

217
Visualizações
Typescript when accessing object that doesn't have such property (possibly not exist)

For example I have this data on JS

const obj = { // never have 'c' property
  a: 1,
  b: 2,
}
const keys = ['a', 'b', 'c'] // always 'a'|'b'|'c' --> ex: [a,b,c] / [c,b,a] / [a,c]

const firstKey = keys[0]
const selectedObj = obj?.[firstKey] || 99

Now how to do it in typescript? I have tried it but stucked with such solution

type Keys = 'a' | 'b' | 'c'

type ObjKey = Exclude<Keys, 'c'>

type Obj = Record<ObjKey, number>

const obj: Obj = {
  a: 1,
  b: 2,
}
const keys: Keys[] = ['a', 'b', 'c']

const firstKey = keys[0] as ObjKey // --> I don't think this is right
const selectedObj = obj?.[firstKey] || 99

I don't think this is right, because by doing so I remove the possibility of runtime check on firstKey to have value 'c'. Wonder what is the correct/proper way to fix this ya? I want to be able to access the selectedObj, but TS scream that

Property 'c' does not exist on type 'Obj'
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

All you need to do is to change the following line:

type Obj = Record<ObjKey, number>

to

type Obj = Partial<Record<Keys, number>>

Explanation:

In your question, you expressed a desire for TypeScript to raise a warning/error that the accessed obj?.[firstKey] property may not be defined which would force the developer to add a runtime check on it. In the example provided, we can see that all of the obj properties are defined and TypeScript will immediately complain about its use during runtime. The way to get around is to make all of the obj properties optional by using the Partial utility type. This will tell TypeScript that the property being accessed may or may not be defined, hence the developer will need to add code to use it.

Here is a ts playground link.

about 4 years ago · Juan Pablo Isaza Relatório

0

In your case, where you mentioned that the object keys won't be changed, I would suggest you to replace this:

type Keys = 'a' | 'b' | 'c'
type ObjKey = Exclude<Keys, 'c'>

with:

const keys = ['a', 'b', 'c'] as const;
type ObjKey = Exclude<typeof keys[number], 'c'>

By doing this you are creating a typescript construct called const assertion that allows you to have an unmutable object.

More docs here: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-4.html#const-assertions

You can then normally use a type annotation on the firstKey variable without receiving any error.

const firstKey: ObjKey = keys[0];
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