Skip to content

typeof with template literal does not narrow union #20949

@canac

Description

@canac

TypeScript Version: 2.7.0-dev.20171230

Code

interface ProcessEnv {
  [key: string]: string | undefined;
}

const env: ProcessEnv = { FOO: 'bar' };
const envVar: string | undefined = env.FOO;
if (typeof envVar === `string`) {
  // error TS2532: Object is possibly 'undefined'.
  console.log(envVar.slice(0));
}
if (typeof envVar === 'string') {
  console.log(envVar.slice(0));
}

Expected behavior:
Should compile fine.

Actual behavior:
error TS2532: Object is possibly 'undefined'. typeof envVar === `string` does not narrow the string | undefined union down to string.

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugA bug in TypeScriptFixedA PR has been merged for this issueHelp WantedYou can do this

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions