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

Using && with a string produces union type with empty string #32455

Open
lumaxis opened this issue Jul 17, 2019 · 3 comments
Open

Using && with a string produces union type with empty string #32455

lumaxis opened this issue Jul 17, 2019 · 3 comments
Labels
Bug A bug in TypeScript
Milestone

Comments

@lumaxis
Copy link

lumaxis commented Jul 17, 2019

The below code is a super simplified version of a real world scenario I just ran into. When trying to assign a value only if some other condition is true and otherwise returning undefined, TypeScript produces a strange union type that includes empty string ''.
The linked Playground contains a slightly larger example that gets closer to demonstrating my real world use case.

I would argue that in cases where the compiler can clearly know that something is truthy, it should evaluate to the type of the value on the right hand side of &&, even with strictNullChecks off.

TypeScript Version: 3.5.1 (With strictNullChecks off)

Search Terms: logical and empty string, string && empty

Code

const x = true && 'a'

Expected behavior:
Type of x is 'a'

Actual behavior:
Type of x is '' | 'a'

Playground Link:
https://www.typescriptlang.org/play/?strictNullChecks=false#code/C4TwDgpgBAysBOBLAdgcwKrMQe2VAvFAOQCGRUAPsQEZECwAUIwGYCuyAxsDnqhMHFbNmACgCUALlgIUGLLkpR2AEwjMUEZVADejKPqgdcAZ2BQANthKqthBKwgBuPQfj9W8PAFkSwABYAdPAkyMrYALbiUAD8FlY2UABkicRkUFIqahrKzgwAvkA

Related Issues:
Couldn't find any 🕵🏼‍♂️

@AnyhowStep
Copy link
Contributor

AnyhowStep commented Jul 17, 2019

//Expected : const y: 1
//Actual : const y: 0 | 1
const y = true && 1;

Playground

//Expected : const y: true
//Actual : const y: false|true (boolean)
const y = true && true;

Playground

@fatcerberus
Copy link

There was another issue about this exact bug that I posted more examples in, but I can't find it now ☹️

@keithlayne
Copy link

Also, with strict null checks on:

declare const foo: any
const x = foo && 1  // 1?

This is pretty dumb to do, but still...

@RyanCavanaugh RyanCavanaugh added the Bug A bug in TypeScript label Jul 26, 2019
@RyanCavanaugh RyanCavanaugh added this to the Backlog milestone Jul 26, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Bug A bug in TypeScript
Projects
None yet
Development

No branches or pull requests

5 participants