Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

typeof with template literal does not narrow union #20949

Closed
canac opened this issue Dec 30, 2017 · 3 comments
Closed

typeof with template literal does not narrow union #20949

canac opened this issue Dec 30, 2017 · 3 comments
Labels
Bug A bug in TypeScript Fixed A PR has been merged for this issue Help Wanted You can do this

Comments

@canac
Copy link

canac commented Dec 30, 2017

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.

@RyanCavanaugh RyanCavanaugh added Help Wanted You can do this Bug A bug in TypeScript labels Jan 2, 2018
@RyanCavanaugh
Copy link
Member

Doesn't really matter, but I'm curious why you wrote it that way?

@canac
Copy link
Author

canac commented Jan 2, 2018

@RyanCavanaugh After reading this article a while back, I became persuaded of template literals' superiority over normal single/double quoted strings and have been using them exclusively ever since.

@mhegazy mhegazy added this to the Community milestone Jan 4, 2018
@mhegazy mhegazy modified the milestones: Community, TypeScript 2.7 Jan 8, 2018
@mhegazy mhegazy added the Fixed A PR has been merged for this issue label Jan 8, 2018
@mhegazy
Copy link
Contributor

mhegazy commented Jan 8, 2018

thanks @Kingwl !

@microsoft microsoft locked and limited conversation to collaborators Jul 3, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Bug A bug in TypeScript Fixed A PR has been merged for this issue Help Wanted You can do this
Projects
None yet
Development

No branches or pull requests

3 participants