gvergnaud / ts-pattern

🎨 The exhaustive Pattern Matching library for TypeScript, with smart type inference.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

P.when doesn't work with .exhaustive() when type guard input doesn't match

migueloller opened this issue · comments

Describe the bug

This does not fail, which is a bug:

function isNumber(value: number | string): value is number {
  return typeof value === 'number'
}

const val = 1 as number | string | null

match([val])
  .with([P.when(isNumber)], () => 'number')
  .exhaustive()

This does fail, which shows the desired behavior:

function isNumber(value: unknown): value is number {
  return typeof value === 'number'
}

const val: number | null = 1

match([val as number | null])
  .with([P.when(isNumber)], () => 'number')
  .exhaustive() // type error

This also fails since the input satisfies the parameter in isNumber

function isNumber(value: number | string | null): value is number {
  return typeof value === 'number'
}

const val: number | null = 1

match([val as number | null])
  .with([P.when(isNumber)], () => 'number')
  .exhaustive() // type error

Code Sandbox with a minimal reproduction case
https://codesandbox.io/s/jovial-thunder-nsg2gc

Versions

  • TypeScript version: 5.1.6
  • ts-pattern version: 5.0.5
  • environment: N/A