Skip to content

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

Closed
@zhuravlikjb

Description

@zhuravlikjb
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?

Metadata

Metadata

Assignees

No one assigned

    Labels

    QuestionAn issue which isn't directly actionable in code

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions