Recently at work, I encountered this code snippet and was left wondering why Typescript couldn't comprehend the logic behind it. If 'test' in the object can either be undefined or a string, shouldn't it logically infer that within an if statement, 'test' must be treated as a string?
interface IObj {
test?: string;
}
const obj: IObj = {
test: "why does this not work?",
};
if (obj.test) {
const { test } = obj;
() => testFunc(obj.test); // error (why does this not work?)
() => testFunc(test); // works
}
function testFunc(testString: string) {
return testString;
}
- I define an object (obj) with an optional property 'test'.
- I then proceed to verify the value of 'test' within an if condition.
The interesting thing is that destructuring works perfectly fine, except if you attempt to utilize the object and its value simultaneously.