From c4483f073e8357106c43f481c3f1aefb82c637a4 Mon Sep 17 00:00:00 2001 From: Pablo Baleztena Date: Wed, 4 Sep 2024 20:08:34 -0300 Subject: [PATCH] [fabric-core] Add basic array-element utility types --- .../fabric/core/src/array/array-element.spec.ts | 12 ++++++++++++ packages/fabric/core/src/array/array-element.ts | 17 +++++++++++++++++ packages/fabric/core/src/array/index.ts | 1 + packages/fabric/core/src/index.ts | 1 + 4 files changed, 31 insertions(+) create mode 100644 packages/fabric/core/src/array/array-element.spec.ts create mode 100644 packages/fabric/core/src/array/array-element.ts create mode 100644 packages/fabric/core/src/array/index.ts diff --git a/packages/fabric/core/src/array/array-element.spec.ts b/packages/fabric/core/src/array/array-element.spec.ts new file mode 100644 index 0000000..d345bd4 --- /dev/null +++ b/packages/fabric/core/src/array/array-element.spec.ts @@ -0,0 +1,12 @@ +import { describe, expectTypeOf, test } from "vitest"; + +describe("ArrayElement utils", () => { + test("Given an array, it should return the element type of the array", () => { + type ArrayElement = + T extends readonly (infer U)[] ? U : never; + + type result = ArrayElement<["a", "b", "c"]>; + + expectTypeOf().toEqualTypeOf<"a" | "b" | "c">(); + }); +}); diff --git a/packages/fabric/core/src/array/array-element.ts b/packages/fabric/core/src/array/array-element.ts new file mode 100644 index 0000000..cb1c634 --- /dev/null +++ b/packages/fabric/core/src/array/array-element.ts @@ -0,0 +1,17 @@ +/** + * Get the element type of an array. + */ +export type ArrayElement = + T extends readonly (infer U)[] ? U : never; + +/** + * Get the first element type of a tuple. + */ +export type TupleFirstElement = + T extends readonly [infer U, ...unknown[]] ? U : never; + +/** + * Get the LAST element type of a tuple. + */ +export type TupleLastElement = + T extends readonly [...unknown[], infer U] ? U : never; diff --git a/packages/fabric/core/src/array/index.ts b/packages/fabric/core/src/array/index.ts new file mode 100644 index 0000000..9062f34 --- /dev/null +++ b/packages/fabric/core/src/array/index.ts @@ -0,0 +1 @@ +export * from "./array-element.js"; diff --git a/packages/fabric/core/src/index.ts b/packages/fabric/core/src/index.ts index ffac2ee..1a38f60 100644 --- a/packages/fabric/core/src/index.ts +++ b/packages/fabric/core/src/index.ts @@ -1,3 +1,4 @@ +export * from "./array/index.js"; export * from "./domain/index.js"; export * from "./error/index.js"; export * from "./record/index.js";