From 93e600fcf919e825a6a6bcb9675a4ef90effe252 Mon Sep 17 00:00:00 2001 From: Mark Probst Date: Fri, 12 Apr 2024 22:08:19 -0400 Subject: [PATCH] Add `isArray` --- package.json | 2 +- src/index.ts | 21 +++++++++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/package.json b/package.json index cb1384e..987cd29 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@glideapps/ts-necessities", - "version": "2.2.2", + "version": "2.2.3", "description": "Small utilities to make life with TypeScript easier", "main": "dist/index.js", "types": "dist/index.d.ts", diff --git a/src/index.ts b/src/index.ts index 31bc10f..5e736e8 100644 --- a/src/index.ts +++ b/src/index.ts @@ -108,6 +108,27 @@ export function isEnumValue(e: T, x: unknown): x is T[keyof T] return (Object.keys(e) as Array).map(k => e[k]).some(v => v === (x as T[keyof T])); } +/** + * Returns whether `x` is an array. + * + * We have this because `Array.isArray(x)` returns `x is any[]`, which means + * that this code compiles without error, for example: + * + * ```typescript + * function thisShouldNotCompile(x: string | readonly string[]) { + * if (Array.isArray(x)) { + * const s = x[0]; + * s.thisIsAnAny("but it's actually a string"); + * } + * } + * ``` + */ +export function isArray(x: readonly T[] | U): x is readonly T[]; +export function isArray(x: T[] | U): x is T[]; +export function isArray(x: readonly T[] | U): x is readonly T[] { + return Array.isArray(x); +} + /** * Returns whether `obj` has `name` as its own property. */