diff --git a/src/functional/noop.ts b/src/functional/noop.ts index 94cab0b..7179d87 100644 --- a/src/functional/noop.ts +++ b/src/functional/noop.ts @@ -1,4 +1,6 @@ /** * No operation function. */ -export function noop() {} +export function noop() { + // no operation +} diff --git a/src/types/assert.test.ts b/src/types/assert.test.ts index 0511907..2f70724 100644 --- a/src/types/assert.test.ts +++ b/src/types/assert.test.ts @@ -7,6 +7,7 @@ import { assertNotNullish, assertUnreachable, } from './assert.ts'; +import type { Nullish } from './types.ts'; type Value = object | boolean | null | undefined; @@ -55,6 +56,51 @@ describe('assert', () => { }); }); +describe('assert implicit', () => { + it('should assert object properties', () => { + interface Foo { + foo: string; + bar?: number | Nullish; + baz?: string | Nullish; + } + + const fooOptional: Foo = { + foo: 'foo', + }; + + const fooRequired: Foo = { + foo: 'foo', + bar: 1, + baz: 'baz', + }; + + internalAssert(fooRequired.bar && fooRequired.baz); + + expectTypeOf(fooRequired.bar).toEqualTypeOf(); + expectTypeOf(fooRequired.baz).toEqualTypeOf(); + + expect(() => + internalAssert( + fooOptional.bar && fooOptional.baz, + 'bar and baz should be defined', + ), + ).toThrow('bar and baz should be defined'); + }); + + it('should assert discriminated union', () => { + type Foo = { type: 'foo'; foo: string } | { type: 'bar'; bar: number }; + + const foo: Foo = { type: 'foo', foo: 'foo' }; + const bar: Foo = { type: 'bar', bar: 1 }; + + internalAssert(foo.type === 'foo'); + internalAssert(bar.type === 'bar'); + + expectTypeOf(foo).toEqualTypeOf<{ type: 'foo'; foo: string }>(); + expectTypeOf(bar).toEqualTypeOf<{ type: 'bar'; bar: number }>(); + }); +}); + describe('assertDefined', () => { const map = new Map([ ['foo', 'bar'], diff --git a/src/types/assert.ts b/src/types/assert.ts index fcb4fb4..ef2348a 100644 --- a/src/types/assert.ts +++ b/src/types/assert.ts @@ -1,4 +1,4 @@ -import type { Falsy, Nullish } from './types.ts'; +import type { Nullish } from './types.ts'; /** * Basic assertion with (a possible lazy) message. @@ -7,10 +7,10 @@ import type { Falsy, Nullish } from './types.ts'; * @param value * @param message */ -export function assert( - value: T, +export function assert( + value: unknown, message: string | (() => string) = `value ${String(value)} is falsy`, -): asserts value is Exclude { +): asserts value { if (!value) { const finalMessage = typeof message === 'function' ? message() : message; throw new Error(finalMessage);