I saw this at work recently and I was wondering why Typescript doesn't understand the code below. If test is either undefined or a string, shouldn't it understand that it has to be a string if it's in an if statement?
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 create an object (obj) with an optional value "test".
- I check the optional value in an if.
Destructuring works, but not if you use the object and value right away.
delete obj.testrunning at some point after theifbut before() => testFunc(obj.test)executes. What would be the value passed intotestFunc? What would be the value when you use() => testFunc(test)instead?