Skip to content

Commit

Permalink
feat: add unknown export
Browse files Browse the repository at this point in the history
  • Loading branch information
lukeed committed Aug 14, 2024
1 parent 56041e6 commit b9ac7b8
Show file tree
Hide file tree
Showing 3 changed files with 70 additions and 0 deletions.
10 changes: 10 additions & 0 deletions infer.types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -738,3 +738,13 @@ let _pa3 = t.partial(
// @ts-expect-error wrong type
t.string(),
);

// ---
// UNKNOWN
// ---

let u1 = t.unknown();
declare let U1: t.Infer<typeof u1>;
assert<unknown>(U1);

assert<unknown>(123);
36 changes: 36 additions & 0 deletions mod.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,42 @@ describe('Null', () => {
});
});

describe('Unknown', () => {
it('should be a function', () => {
assert(typeof t.unknown === 'function');
});

// https://json-schema.org/understanding-json-schema/reference/null
it('should be JSON schema', () => {
assertEquals(t.unknown(), {
// empty
});
});

it('should allow annotations', () => {
let output = t.unknown({
deprecated: true,
description: 'foobar',
});

assertEquals(output, {
deprecated: true,
description: 'foobar',
});
});

it('should force "type" property', () => {
let output = t.null({
// @ts-expect-error; not in options definition
type: 'other',
});

assertEquals(output, {
type: 'null',
});
});
});

describe('Constant', () => {
it('should be a function', () => {
assert(typeof t.constant === 'function');
Expand Down
24 changes: 24 additions & 0 deletions mod.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ export type Infer<T> =
& { [K in keyof P as P[K] extends _optional<infer _> ? K : never]?: Infer<P[K]> }
& { [K in keyof P as P[K] extends _optional<infer _> ? never : K]: Infer<P[K]> }
>
: T extends _unknown ? unknown
: T;

/**
Expand Down Expand Up @@ -90,6 +91,7 @@ export type Type =
| _object
| _string
| _tuple<unknown>
| _unknown
| _all<unknown>
| _any<unknown>
| _one<unknown>
Expand Down Expand Up @@ -211,6 +213,27 @@ function _null(options?: Omit<_null, 'type'>): _null {
return { ...options, type: 'null' };
}

/**
* An unknown type.
*
* > [!IMPORTANT]
* > Equivalent to `unknown` in TypeScript, which allows any value.
*/
type _unknown = Annotations & {
default?: unknown;
examples?: unknown[];
};

/**
* Defines a schema of unknown type.
*
* > [!IMPORTANT]
* > Equivalent to `unknown` in TypeScript, which allows any value.
*/
function _unknown(options?: _unknown): _unknown {
return options || {};
}

/**
* A constant literal value.
Expand Down Expand Up @@ -817,4 +840,5 @@ export {
_object as object,
_string as string,
_tuple as tuple,
_unknown as unknown,
}

0 comments on commit b9ac7b8

Please sign in to comment.