To prevent a null object error, I attempted to use logical operators. The object in question has attributes including a string and a union type. When I employed the "&&" operator to verify the object's existence, it resulted in evaluating the expression to another union type that includes empty strings, leading to a type mismatch error.
Upon testing with an IF statement instead of the logical operator, the code behaved as expected. However, I am eager to grasp why my original approach did not yield the desired outcome.
type FooType = 'aaa' | 'bbb' | 'ccc';
interface IFoo {
type: FooType;
id: string;
}
type FooAlias = IFoo;
const fooObject = {type: 'aaa', id: '111'} as IFoo;
const fooObject2: FooAlias = {
id: fooObject && fooObject.id,
type: fooObject && fooObject.type
/* An error is flagged on the line above:
Type '"" | "aaa" | "bbb" | "ccc"' is not assignable to type 'FooType'.
Type '""' is not assignable to type 'FooType'.ts(2322)*/
};
Replacing
type: fooObject && fooObject.type
with type: fooObject ? fooObject.type : null
resolved the issue, suggesting that it appropriately handled scenarios where the value might be an empty string.