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.

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

    Issue actions