Reputation:
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
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
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