From 0ec676d651af8bdf8be536588a17ddf19073f830 Mon Sep 17 00:00:00 2001 From: silverwind Date: Thu, 8 Aug 2024 19:25:28 +0200 Subject: [PATCH] Add `EmptyArray` and `IsEmptyArray` Fixes: https://github.com/sindresorhus/type-fest/issues/929 --- index.d.ts | 1 + source/empty-array.d.ts | 32 ++++++++++++++++++++++++++++++++ test-d/empty-array.ts | 28 ++++++++++++++++++++++++++++ 3 files changed, 61 insertions(+) create mode 100644 source/empty-array.d.ts create mode 100644 test-d/empty-array.ts diff --git a/index.d.ts b/index.d.ts index 8c1588260..60e92332c 100644 --- a/index.d.ts +++ b/index.d.ts @@ -9,6 +9,7 @@ export type {KeysOfUnion} from './source/keys-of-union'; export type {DistributedOmit} from './source/distributed-omit'; export type {DistributedPick} from './source/distributed-pick'; export type {EmptyObject, IsEmptyObject} from './source/empty-object'; +export type {EmptyArray, IsEmptyArray} from './source/empty-array'; export type {IfEmptyObject} from './source/if-empty-object'; export type {NonEmptyObject} from './source/non-empty-object'; export type {UnknownRecord} from './source/unknown-record'; diff --git a/source/empty-array.d.ts b/source/empty-array.d.ts new file mode 100644 index 000000000..2be962a47 --- /dev/null +++ b/source/empty-array.d.ts @@ -0,0 +1,32 @@ +/** +Represents a strictly empty array, the `[]` value. + +@example +``` +import type {EmptyArray} from 'type-fest'; + +const bar1: EmptyArray = []; // Pass +const bar2: EmptyArray = {}; // Fail +const bar3: EmptyArray = null; // Fail +``` + +@category Array +*/ +export type EmptyArray = never[]; + +/** +Returns a `boolean` for whether the type is strictly equal to an empty array, the `[]` value. + +@example +``` +import type {IsEmptyArray} from 'type-fest'; + +type Pass = IsEmptyArray<[]>; //=> true +type Fail = IsEmptyArray<{}>; //=> false +type Fail = IsEmptyArray; //=> false +``` + +@see EmptyArray +@category Array +*/ +export type IsEmptyArray = T extends EmptyArray ? true : false; diff --git a/test-d/empty-array.ts b/test-d/empty-array.ts new file mode 100644 index 000000000..ac660ab0d --- /dev/null +++ b/test-d/empty-array.ts @@ -0,0 +1,28 @@ +import {expectAssignable, expectType} from 'tsd'; +import type {EmptyArray, IsEmptyArray} from '../index'; + +declare let foo: EmptyArray; + +expectAssignable(foo); +expectAssignable(foo = []); + +foo = []; +foo = [...[]]; // eslint-disable-line unicorn/no-useless-spread +foo = [...new Set([])]; +const _length = foo.length; + +// @ts-expect-error +foo = [1]; +// @ts-expect-error +foo = [...[1]]; // eslint-disable-line unicorn/no-useless-spread +// @ts-expect-error +foo = [...new Set([1])]; +// @ts-expect-error +foo = null; +// @ts-expect-error +foo.bar = 42; +// @ts-expect-error +foo.bar = []; + +expectType>(true); +expectType>(true);