Closed
Description
Bug Report
π Search Terms
extract to variable accessor, accessor automatically infer
π Version & Regression Information
- This is the behavior in every version I tried, and I searched the FAQ page for
].
β― Playground Link
Playground link with relevant code
π» Code
type T_Object = {
theKey: string;
};
type T_MyType = T_Object | string;
function isItObject(
input: T_MyType
): input is T_Object {
return !!(input as T_Object).theKey;
}
const myVariable: { [key: string]: T_MyType } =
//@ts-ignore
somehowGetSomething();
function myFunctionWithError
(key: string) {
if (isItObject(myVariable[key])) {
console.log('it is object');
return myVariable[key].theKey;
}
return myVariable[key];
}
function myValidFunction
(key: string) {
const extractedVariable = myVariable[key];
if (isItObject(extractedVariable)) {
console.log('it is object');
return extractedVariable.theKey;
}
return myVariable[key];
}
π Actual behavior
There are two functions at the bottom of the code. The only difference is that in second case, I extracted myVariable[key]
to a variable and used that in if condition and return value. In first function it gives me error, but in the second one (extracted variable) it doesn't.
π Expected behavior
I expected TypeScript to automatically infer myVariable[key]
is an object inside the if
condition with isItObject(myVariable[key])