简体   繁体   中英

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}.

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

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

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");
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM