Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Property 'x' does not exist on type when using optional chaining operator

I would like to use optional chaining operator in typescript, but I get the error Property 'dog' does not exist on type '{ name: string; cat: Record<string, string>; }'. . Totally make sense the error complain from typescript but I am wondering if anyway for me to walk around? playground

const adventurer: {name: string;cat:Record<string, string>} = {
  name: 'Alice',
  cat: {
    name: 'Dinah'
  }
};

const dogName = adventurer?.dog;
console.log(dogName);

like image 942
jacobcan118 Avatar asked Jun 29 '26 23:06

jacobcan118


1 Answers

Why does this happen?

You are telling the TS compiler by providing a type for adventurer, that adventurer will never have a property dog (EDIT: thanks @jcalz for pointing out that's not exactly true. Have a look at the comment below for more info). There are two main ways around this:

Tell TypeScript you know better by asserting another type (like any)

const dogName = (adventurer as any)?.dog;
console.log(dogName);

Change the type of adventurer to optionally include dog

const adventurer: {name: string;cat:Record<string, string>; dog?: string} = {
  name: 'Alice',
  cat: {
    name: 'Dinah'
  }
};

const dogName = adventurer?.dog;
console.log(dogName);
like image 164
Taxel Avatar answered Jul 01 '26 21:07

Taxel