I've encountered an interesting issue while working with TypeScript and JavaScript. I created a code snippet that runs perfectly in JavaScript but throws a syntax error in TypeScript. You can check it out in action at this TypeScript Sandbox.
Essentially, the problem arises when attempting to use the||
(OR) operator to handle cases where an object property might be undefined. TypeScript raises an error claiming the property doesn't exist, even though I'm using ||
specifically for that reason.
class Person {
name: string;
job: string;
}
var person1:Person = {name: 'hi', job: 'yes'};
var name = 'bye';
function showName(person1:Person | string ) {
var personsName: string = person1.name || person1;
document.write(personsName);
document.write('<br />');
}
showName(person1);
showName(name);
The expected output is:
hi
bye
However, TypeScript flags a syntax error on person1.name. Why is this happening? And what would be the correct way to address this in TypeScript?