diff --git a/.yarn/cache/tsafe-npm-1.7.2-ab23a08324-a02da1bb81.zip b/.yarn/cache/tsafe-npm-1.7.2-ab23a08324-a02da1bb81.zip new file mode 100644 index 00000000..7b25b60f Binary files /dev/null and b/.yarn/cache/tsafe-npm-1.7.2-ab23a08324-a02da1bb81.zip differ diff --git a/package.json b/package.json index 8a44153f..60e12ae4 100644 --- a/package.json +++ b/package.json @@ -44,6 +44,7 @@ "git-cz": "4.9.0", "prettier": "3.2.5", "ts-node": "10.9.2", + "tsafe": "^1.7.2", "typedoc": "^0.25.13", "typedoc-plugin-missing-exports": "^2.2.0", "typescript": "^5.4.5", diff --git a/src/Optional.spec.ts b/src/Optional.spec.ts index bf43e5ff..58bdfbf3 100644 --- a/src/Optional.spec.ts +++ b/src/Optional.spec.ts @@ -1,5 +1,5 @@ import { expect, describe, test, vi } from 'vitest'; - +import {assert, Equals} from "tsafe"; import { Optional } from './Optional.js'; import { NoSuchElementException } from './exceptions/NoSuchElementException.js'; @@ -119,6 +119,16 @@ describe('Optional', () => { .isPresent() ).toBe(false); }); + test('filters to a new type if given a type guard', () => { + type A = { x: number}; + type B = A & { z: string}; + const a: A = { x: 1}; + const oA = Optional.of(a); + const filtered = oA.filter((x): x is B => 'z' in x); + + assert>>(true); + + }); }); describe('#toJSON', () => { test('returns undefined when JSON stringified', () => { diff --git a/src/Optional.ts b/src/Optional.ts index e53f56cd..a47fe334 100644 --- a/src/Optional.ts +++ b/src/Optional.ts @@ -45,6 +45,8 @@ export class Optional { return new Optional>(value as NonNullable); } + filter(predicate: (v: T) => v is S): Optional; + filter(predicate: (v: T) => boolean): Optional /** * Checks the value of the optional. If it matches the `predicate`, then a non-empty * Optional of the same value will be returned. @@ -53,7 +55,7 @@ export class Optional { * * @param predicate */ - filter(predicate: (v: T) => boolean): Optional { + filter(predicate: (v: T) => v is S): Optional { if (haveValue(this.value) && predicate(this.value)) { return new Optional(this.value); } diff --git a/yarn.lock b/yarn.lock index f571b3d2..cf4ca20b 100644 --- a/yarn.lock +++ b/yarn.lock @@ -442,6 +442,7 @@ __metadata: git-cz: 4.9.0 prettier: 3.2.5 ts-node: 10.9.2 + tsafe: ^1.7.2 typedoc: ^0.25.13 typedoc-plugin-missing-exports: ^2.2.0 typescript: ^5.4.5 @@ -6139,6 +6140,13 @@ __metadata: languageName: node linkType: hard +"tsafe@npm:^1.7.2": + version: 1.7.2 + resolution: "tsafe@npm:1.7.2" + checksum: a02da1bb81fed3c35b1ce1ea5f6118a632c436d41536ca7a8a399d5890add53a0352da6f48b5fbb66d9f80c66c71de45de6071f696781fa03e738058d112ee80 + languageName: node + linkType: hard + "tslib@npm:^2.1.0": version: 2.6.2 resolution: "tslib@npm:2.6.2"