feat(typescript-types): Add IsUnknown<T>

This commit is contained in:
T. R. Bernstein
2025-07-17 16:37:40 +02:00
parent 96cf6bbc48
commit 527250a98a
3 changed files with 22 additions and 0 deletions

View File

@@ -25,6 +25,7 @@ The types included in this library are categorized by their purpose.
| [`IsAny<T>`][] | `true` if `T` is `any`, `false` otherwise (`null`, `undefined` also yield `false`) |
| [`IsNever<T>`][] | `true` if `T` is `never`, `false` otherwise (`null`, `undefined`, `any` also yield `false`) |
| [`IsUndefined<T>`][] | `true` if `T` is `undefined`, `false` otherwise (`null`, `never`, `any` also yield `false`). |
| [`IsUnknown<T>`][] | `true` if `T` is `unknown`, `false` otherwise (`null`, `never`, `any` also yield `false`). |
| [`If<Test, TrueBranch, FalseBranch>`][] | Returns `TrueBranch` if `Test` is `true`, `FalseBranch` otherwise[^if_remark]. |
| [`IsKeyOf<T, K>`][] | `true` if `K` is a key of `T`, `false` otherwise. If `T` is `any`, any `K` but `never` will yield `true`. |
| [`IsEmptyString<S>`][] | `true` if `S` is the empty string `''`, `false` otherwise.[^is-empty-string_remark] |
@@ -36,6 +37,7 @@ The types included in this library are categorized by their purpose.
[`IsAny<T>`]: src/is-any.ts
[`IsNever<T>`]: src/is-never.ts
[`IsUndefined<T>`]: src/is-undefined.ts
[`IsUnknown<T>`]: src/is-unknown.ts
[`If<Test, TrueBranch, FalseBranch>`]: src/if.ts
[`IsKeyOf<T, K>`]: src/is-key-of.ts
[`IsEmptyString<S>`]: src/is-empty-string.ts

View File

@@ -0,0 +1,9 @@
import type { If } from './if.js'
import type { IsAny } from './is-any.js'
import type { IsNever } from './is-never.js'
export type IsUnknown<T> = If<
IsAny<T>,
false,
If<IsNever<T>, false, T extends unknown ? (unknown extends T ? true : false) : false>
>

View File

@@ -0,0 +1,11 @@
import type { IsUnknown } from '@/is-unknown.js'
import { expect } from 'tstyche'
expect<IsUnknown<unknown>>().type.toBe<true>()
expect<IsUnknown<1>>().type.toBe<false>()
expect<IsUnknown<'somestring'>>().type.toBe<false>()
expect<IsUnknown<null>>().type.toBe<false>()
expect<IsUnknown<undefined>>().type.toBe<false>()
expect<IsUnknown<any>>().type.toBe<false>()
expect<IsUnknown<never>>().type.toBe<false>()