Skip to content

Commit

Permalink
Change type guards to return never instead of false in option
Browse files Browse the repository at this point in the history
Previously when invoking the `isSome` on None type or `isNone` on Some
type would return always false and the corresponding type would be set
as the original type. This however does not work with the newest
TypeScript version `5.5.3`. The failure in this case is correct as the
inference does not work as expected if a false is returned instead of a
type guard.

The 'correct' change here is to instead return never type guard as we
can never enter that block that checks for isNone or isSome on a type
that does not reflect it.

Example:
```ts
const some = Some(42);

// Previously this was accepted and the type was inferred as Some in the
// code block
if (some.isNone()) {
  some;
  // ^? Some<number>;
}

// However now the type would be never, which is less flexible, but
// correct behaviour
if (some.isNone()) {
  some;
  // ^? never
}
```
  • Loading branch information
erikjuhani committed Jul 9, 2024
1 parent 4aea7bd commit 3a11cc7
Show file tree
Hide file tree
Showing 2 changed files with 4 additions and 4 deletions.
4 changes: 2 additions & 2 deletions option/option.ts
Original file line number Diff line number Diff line change
Expand Up @@ -686,7 +686,7 @@ export class Some<T> extends Option<T> {
}

/** {@link Option.isNone} */
isNone(): false {
isNone(): this is never {
return false;
}

Expand Down Expand Up @@ -757,7 +757,7 @@ export class None extends Option<never> {
}

/** {@link Option.isSome} */
isSome(): false {
isSome(): this is never {
return false;
}

Expand Down
4 changes: 2 additions & 2 deletions option/option_test_types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ import { assertType, type IsExact } from "@std/testing/types";
const option2 = Some(42);

if (option2.isNone()) {
assertType<IsExact<typeof option2, Some<42>>>(true);
assertType<IsExact<typeof option2, never>>(true);
}

if (Option.isNone(option2)) {
Expand All @@ -123,7 +123,7 @@ import { assertType, type IsExact } from "@std/testing/types";
}

if (option3.isSome()) {
assertType<IsExact<typeof option3, None>>(true);
assertType<IsExact<typeof option3, never>>(true);
}

if (Option.isSome(option3)) {
Expand Down

0 comments on commit 3a11cc7

Please sign in to comment.