fix(.exhaustive): optional discriminant
This PR fixes #278
This new release fixes the following bug in exhaustiveness checking when matching on optional properties:
```ts
type Input = { type?: 'one' } | { type: 'two' };
const f1 = (input: Input) =>
match(input)
.with({ type: 'one' }, () => {})
.with({ type: 'two' }, () => {})
.exhaustive(); // shouldn't type-check, but does 👎
const f2 = (input: Input) =>
match(input)
.with({ type: 'one' }, () => {})
.with({ type: 'two' }, () => {})
.with({ type: undefined }, () => {}) // <- the type key needs to be present.
.exhaustive(); // shouldn't type-check, but does 👎
```
These two cases don't type check anymore. They fail with a `NonExhaustiveError<{ type?: undefined; }>`. To fix it, you should do:
```ts
type Input = { type?: 'one' } | { type: 'two' };
const f = (input: Input) =>
match(input)
.with({ type: 'one' }, () => {})
.with({ type: 'two' }, () => {})
.with({ type: P.optional(undefined) }, () => {}) // <- the type property may not be there
.exhaustive(); // ✅
```
This is a purely type-level change, the runtime behavior is still the same.
合并状态:已合并 合并于 2025-05-18 关闭于 2025-05-18 0 条评论