Skip to content

Commit

Permalink
feat: added AsNumericArray<T> utility
Browse files Browse the repository at this point in the history
  • Loading branch information
yankeeinlondon committed Sep 16, 2024
1 parent 76f77bd commit 9c86e29
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 1 deletion.
22 changes: 22 additions & 0 deletions src/types/lists/AsNumericArray.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { AllLiteral } from "../boolean-logic";
import { RemoveNever } from "../containers";
import { NumberLike } from "../numeric-literals";
import { AsNumber } from "../type-conversion";


/**
* **AsNumericArray**`<T>`
*
* Converts into a numeric array:
*
* - `number` values are proxied through
* - `${number}` values are converted to a number
* - all other types are converted to `never` and removed
*/
export type AsNumericArray<T> = T extends readonly unknown[]
? RemoveNever<{
[K in keyof T]: T[K] extends NumberLike
? AsNumber<T[K]>
: never
}>
: never;
4 changes: 3 additions & 1 deletion src/types/lists/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ export * from "./FilterLiterals";
export * from "./FilterWideTypes";
export * from "./Length";
export * from "./Last";
export * from "./MaxLength";
export * from "./IndexOf";
export * from "./UnionFromProp";
export * from "./Flatten";
Expand Down Expand Up @@ -50,7 +51,8 @@ export * from "./ToCSV";
export * from "./Push"
export * from "./TakeFirst"
export * from "./TakeLast"

export * from "./Sort"
export * from "./AsNumericArray";


// #endregion auto-indexed files
Expand Down
28 changes: 28 additions & 0 deletions tests/lists/AsNumericArray.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { Equal, Expect } from "@type-challenges/utils";
import { AsNumericArray } from "src/types/index";
import { describe, it } from "vitest";

// Note: while type tests clearly fail visible inspection, they pass from Vitest
// standpoint so always be sure to run `tsc --noEmit` over your test files to
// gain validation that no new type vulnerabilities have cropped up.

describe("AsNumericArray<T>", () => {

it("happy path", () => {
type NoChange = AsNumericArray<[1,2,3]>;
type Mixed = AsNumericArray<[1,2,`3`]>;
type StrLit = AsNumericArray<[`1`,`2`,`3`]>;

type IgnoreInvalid = AsNumericArray<[1,2,null,false,3]>;

// @ts-ignore
type cases = [
Expect<Equal<NoChange, [1,2,3]>>,
Expect<Equal<Mixed, [1,2,3]>>,
Expect<Equal<StrLit, [1,2,3]>>,

Expect<Equal<IgnoreInvalid, [1,2,3]>>
];
});

});

0 comments on commit 9c86e29

Please sign in to comment.