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

Is there a special 'hack' for operators and string literal types? #6505

Closed
zhuravlikjb opened this issue Jan 15, 2016 · 4 comments
Closed

Is there a special 'hack' for operators and string literal types? #6505

zhuravlikjb opened this issue Jan 15, 2016 · 4 comments
Labels
Question An issue which isn't directly actionable in code

Comments

@zhuravlikjb
Copy link

type WeekDay = "Monday" | "Tuesday" | "Wednesday" | "Thursday" | "Friday" | "Saturday" | "Sunday";

function doFun(a: WeekDay | WeekDay[]) {
    a = "Monday";  // string literal is contextually typed, so it has string literal type "Monday" => no type mismatch
    if (a === "Monday") { // string literal is NOT contextually typed and has type 'string' => should be type mismatch error

    }
}

Type mismatch error in the second case should be because:

  1. we're comparing 'string' with "Monday" | "Tuesday" | "Wednesday" | "Thursday" | "Friday" | "Saturday" | "Sunday" | ("Monday" | "Tuesday" | "Wednesday" | "Thursday" | "Friday" | "Saturday" | "Sunday")[] for assignability in both directions
  2. according to the spec, in direction 'string' => the-other-type, we're comparing 'string' with all union type constituents, and it's not assignable to any of them => fail
  3. according to the spec, in direction the-other-type => 'string', all constituents of the-other-type should be assignable to 'string', but obviously Array is not assignable to it => fail
  4. both conditions fail => type mismatch error for '===' operator

But by some reason the compiler doesn't show any errors here.

Is there some special handling of string literal types with operators like '===', switch labels, etc?

@zhuravlikjb
Copy link
Author

Ah, I've found it, sorry:
8dbfe1c

@RyanCavanaugh RyanCavanaugh added the Question An issue which isn't directly actionable in code label Jan 15, 2016
@DanielRosenwasser
Copy link
Member

We have two alternative proposals to solving this better. One is inferring string literal types at comparison locations (see the PR at #6196), and the other is described on #6167 (comment).

@zhuravlikjb
Copy link
Author

Thanks a lot, Daniel! Will track both PRs to see the final decision taken.

@DanielRosenwasser
Copy link
Member

@zhuravlikjb things are leaning towards literal locations.

@microsoft microsoft locked and limited conversation to collaborators Jun 19, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Question An issue which isn't directly actionable in code
Projects
None yet
Development

No branches or pull requests

3 participants