Fact:
I am currently using TS version 2.3.4. I have developed a function that checks if a variable is defined (it takes the parameter variable
and returns 'undefined' !== typeof variable
). It's quite simple.
export function IsDefined(variable: any): boolean {
return 'undefined' !== typeof variable;
}
Issue: The code snippet below triggers a warning on the second line. The warning message reads Object is possibly undefined.
if (IsDefined(myVar)) {
myVar.mockProperty = "asdf"; // Object (myVar) is possibly undefined
}
Question: Is there a way to inform the TypeScript compiler that the IsDefined()
method validates variables against undefined values, so it doesn't generate false warnings? Are there alternative approaches to address this issue?
Workarounds I am aware of and prefer not to use as they make the code messy:
(<myType>myVar).mockProperty = "asdf";
if ("undefined" !== typeof myVar) {