From f805d07a549963c9a626a889c9cceae89d1c6b48 Mon Sep 17 00:00:00 2001 From: BaoLong Wang Date: Sun, 11 Aug 2024 13:05:35 +0800 Subject: [PATCH] Add `Arrayable` type #270 --- index.d.ts | 1 + readme.md | 1 + source/arrayable.d.ts | 25 +++++++++++++++++++++++++ test-d/arrayable.ts | 9 +++++++++ 4 files changed, 36 insertions(+) create mode 100644 source/arrayable.d.ts create mode 100644 test-d/arrayable.ts diff --git a/index.d.ts b/index.d.ts index 8c1588260..cdce30faf 100644 --- a/index.d.ts +++ b/index.d.ts @@ -36,6 +36,7 @@ export type {UndefinedOnPartialDeep} from './source/undefined-on-partial-deep'; export type {ReadonlyDeep} from './source/readonly-deep'; export type {LiteralUnion} from './source/literal-union'; export type {Promisable} from './source/promisable'; +export type {Arrayable} from './source/arrayable'; export type {Opaque, UnwrapOpaque, Tagged, GetTagMetadata, UnwrapTagged} from './source/opaque'; export type {InvariantOf} from './source/invariant-of'; export type {SetOptional} from './source/set-optional'; diff --git a/readme.md b/readme.md index 231804811..72dbf1b2b 100644 --- a/readme.md +++ b/readme.md @@ -272,6 +272,7 @@ type ShouldBeNever = IfAny<'not any', 'not never', 'never'>; ### Array +- [`Arrayable`](source/arrayable.d.ts) - Create a type that represents either the value or array of the value. - [`Includes`](source/includes.d.ts) - Returns a boolean for whether the given array includes the given item. - [`Join`](source/join.d.ts) - Join an array of strings and/or numbers using the given string as a delimiter. - [`ArraySlice`](source/array-slice.d.ts) - Returns an array slice of a given range, just like `Array#slice()`. diff --git a/source/arrayable.d.ts b/source/arrayable.d.ts new file mode 100644 index 000000000..75390789c --- /dev/null +++ b/source/arrayable.d.ts @@ -0,0 +1,25 @@ +/** +Create a type that represents either the value or array of the value. + +@see Promisable + +@example +``` +import type {Arrayable} from 'type-fest'; + +function bundle(input: string, output: Arrayable) { + const outputList = Array.isArray(output) ? output : [output]; + // ... + + for (const output of outputList) { + console.log(`write to: ${output}`); + } +} + +bundle('src/index.js', 'dist/index.js'); +bundle('src/index.js', ['dist/index.cjs', 'dist/index.mjs']); +``` + +@category Array +*/ +export type Arrayable = T | T[]; diff --git a/test-d/arrayable.ts b/test-d/arrayable.ts new file mode 100644 index 000000000..ed80cca1c --- /dev/null +++ b/test-d/arrayable.ts @@ -0,0 +1,9 @@ +import {expectType} from 'tsd'; +import type {Arrayable} from '../index'; + +declare const unknown: unknown; + +expectType>(unknown as string | string[]); +expectType>(unknown as (string | {foo: number}) | Array); +expectType>(unknown as /* never | */ never[]); +expectType>(unknown as string[] | string[][]);