Skip to content

Commit

Permalink
Add isArray
Browse files Browse the repository at this point in the history
  • Loading branch information
schani committed Apr 13, 2024
1 parent 1456874 commit 93e600f
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -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",
Expand Down
21 changes: 21 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,27 @@ export function isEnumValue<T extends object>(e: T, x: unknown): x is T[keyof T]
return (Object.keys(e) as Array<keyof T>).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<T, U>(x: readonly T[] | U): x is readonly T[];
export function isArray<T, U>(x: T[] | U): x is T[];
export function isArray<T, U>(x: readonly T[] | U): x is readonly T[] {
return Array.isArray(x);
}

/**
* Returns whether `obj` has `name` as its own property.
*/
Expand Down

0 comments on commit 93e600f

Please sign in to comment.