Skip to content

String literal type comparison should result in an error if the compared value is invalid #7112

Closed
@NoelAbrahams

Description

@NoelAbrahams

Hi,

We have been adding compile time safety to the magic string problem through the excellent string literal type introduced in 1.8.

One case that we are finding slipping through the safety net is the following:

type Foo = 'a' | 'b';

const foo: Foo = 'a';

if (foo === 'bar') {
}

Here the Foo type is being compared to an incompatible value 'bar'.

It would be nice to get an error here similar to an enum comparison error:

enum Foo { a, b }
enum Bar { a, b }
let foo: Foo;

if (foo === Bar.a) { // Operator '===' cannot be applied to types 'Foo' and 'Bar'
}

This is especially useful for obtaining a compile time error when the original strings ('a' | 'b') are refactored during the course of development.

I'm aware that there are workarounds involving pseudo string enums, but this is a suggestion for this primitive case.

Thanks.

Activity

DanielRosenwasser

DanielRosenwasser commented on Feb 18, 2016

@DanielRosenwasser
Member

This looks like a duplicate of #6149. The general issue is discussed at #6167. A fix exists at #6196.

RyanCavanaugh

RyanCavanaugh commented on Jul 29, 2019

@RyanCavanaugh
Member

This has been fixed

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    In DiscussionNot yet reached consensusSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @DanielRosenwasser@NoelAbrahams@RyanCavanaugh@mhegazy

        Issue actions

          String literal type comparison should result in an error if the compared value is invalid · Issue #7112 · microsoft/TypeScript