Type Inference vs. Type Assertion in TypeScript
Two important tools in the TypeScript type system are type inference and type assertion. While they sound similar, they serve different purposes and …
To define an array of minimal length we have to create an array of defined length and then extend it with an array of unknown length.
Array of certain length can be done in few ways
// classical array
type ArrayOfOne<T> = [T];
type ArrayOfTwo<T> = [T, T];
// object-like list
type ArrayOfOne<T> = { 0: T };
type ArrayOfTwo<T> = { 0: T, 1: T};
And the extension can be done with intersection or with spread operator.
// Intersection
type ArrayOfOneAndMore<T> = [T] & T[];
type ArrayOfOneAndMore2<T> = ArrayOfOne & T[];
type ArrayOfOneAndMore3<T> = { 0: T } & T[];
// Spread operator
type ArrayOfOneAndMore<T> = [T, ...T[]];
type ArrayOfOneAndMore2<T> = [ArrayOfOne, ...T[]];
type ArrayOfOneAndMore3<T> = [{ 0: T }, ...T[]];
We can now use the types to ensure that the array has the required minimal length.
function example(items: ArrayOfOneAndMore<number>) {}
// Error: Source has 0 element(s) but target requires 1.
example([]);
// Valid
example([1]);
example([1, 2]);
example([1, 2, 3]);
I personally prefer using the spread operator which is easier for me to read and grasp. And also the typescript warning message is much easier to understand.
Two important tools in the TypeScript type system are type inference and type assertion. While they sound similar, they serve different purposes and …
Understanding the Difference Between void and never in TypeScript When working with TypeScript, we may encounter various utility types that help …