Skip to content

TS does not automatically understand object with accessor type if not extracted to a variableΒ #46111

@aghArdeshir

Description

@aghArdeshir

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])

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions