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

.exhaustive() does not cause TS error when using instanceOf #264

Open
BenLorantfy-AB opened this issue Jun 17, 2024 · 1 comment
Open

.exhaustive() does not cause TS error when using instanceOf #264

BenLorantfy-AB opened this issue Jun 17, 2024 · 1 comment

Comments

@BenLorantfy-AB
Copy link

Describe the bug
The exhaustive() function does not raise a TS error when instanceOf is used and not all possible classes are handled

TypeScript playground with a minimal reproduction case

Example: Playground

In the above example, I would expect that exhaustive() to raise a NonExhaustiveError error because ClassB is not handled

Versions

  • TypeScript version: 5.4.5
  • ts-pattern version: 4.0.1
@gvergnaud
Copy link
Owner

gvergnaud commented Jun 17, 2024

This is unfortunately a limitation from the TypeScript type system – structural typing makes it consider two classes with different names as the same type, unless they contain a discriminant property to distinguish them.

class ClassA {}
class ClassB {}

type T = Exclude<ClassA | ClassB, ClassA>
//   ^? never

In this case, you could expect T to be of type ClassB, but it isn't.

One workaround is to give them a discriminant property:

class ClassA {
   type = "ClassA" as const
}

class ClassB {
   type = "ClassB" as const
}

let err2: ClassA | ClassB = new ClassB();

const result2 = match(err2)
   .with(P.instanceOf(ClassA), (result) => "classA")
   .exhaustive(); // ❌

Playground

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants