user11522807
user11522807

Reputation:

How to tell a typescript that value is an empty object?

Here is my code.

function DD(x: { y: string } | {}) {
  if (x.y) {//error
   console.log("DD jingo");
  }
}

I get this error The property "y" does not exist in the type "{} | {y: string;}".The property "y" does not exist in the type "{}".

I am new to typescript. How to say that X can accept an empty object and {y: string}.

Upvotes: 5

Views: 151

Answers (2)

Robert Cooper
Robert Cooper

Reputation: 2250

Not sure if this is a good pattern in TypeScript, but you could explicitly tell TypeScript that your value of x is of the type { y: string } in your if statement:

function DD(x: { y: string } | {}) {
  if ((x as {y: string}).y) {
   console.log("DD jingo");
  }
}

Upvotes: 0

Robby Cornelissen
Robby Cornelissen

Reputation: 97331

You can mark the y property as optional, using ?:

function DD(x: { y?: string }) {
  if (x.y) {
   console.log("DD jingo");
  }
}

Upvotes: 2

Related Questions