Home > database >  How to define a custom TypeScript definition of an array where all elements are number except first
How to define a custom TypeScript definition of an array where all elements are number except first

Time:11-23

The arrays in question are SVG path segments, for instance ['L', 0, 0] I'm basically using this to define these arrays:

// doSomethingToSegment.js

/** @type {Object.<string, number>} */
const paramsCount = {
  a: 7, c: 6, h: 1, l: 2, m: 2, r: 4, q: 4, s: 4, t: 2, v: 1, z: 0,
};
  
/**
 * This definition is WRONG, FIX ME!!
 *
 * @typedef {(string|number)[]} segment
 */

/**
 * Check segment validity.
 *
 * @param {segment} seg input segment
 * @return {boolean} segment is/not valid
 */
function checkSegment(seg) {
  const [pathCommand] = seg;
  const LK = pathCommand.toLowerCase();
  const UK = pathCommand.toUpperCase();
  const segmentValues = seg.slice(1);
  const expectedAmount = paramsCount[LK];

  return checkPathCommand(UK) && checkPathValues(segmentValues, expectedAmount);
}

/**
 * @param {string} ch input character
 * @returns {boolean} true when `ch` is path command
 */
function checkPathCommand(ch) {
  return ('ACHLMRQSTVZ').includes(ch);
}

/**
 * @param {Number[]} values input values
 * @param {Number} expected amount
 * @return {boolean} segment has/not the right amount of valid numbers
 */
function checkPathValues(values, expected) {
  return values.length === expected && values.every(x => !Number.isNaN(x));
}

Now the pathCommand.toLowerCase() call throws this error:

Property 'toLowerCase' does not exist on type 'string | number'.
  Property 'toLowerCase' does not exist on type 'number'.

And the segmentValues throws this one:

Argument of type '(string | number)[]' is not assignable to parameter of type 'number[]'.
  Type 'string | number' is not assignable to type 'number'.
    Type 'string' is not assignable to type 'number'.

So, how to define a custom type definition @type {WHAT} segment) that satisfies this specific need?

CodePudding user response:

type A = [string, ...number[]];

More info about rest elements in tuple types: https://www.typescriptlang.org/docs/handbook/2/objects.html#tuple-types

Here are examples from the docs:

Tuples can also have rest elements, which have to be an array/tuple type.

type StringNumberBooleans = [string, number, ...boolean[]];
type StringBooleansNumber = [string, ...boolean[], number];
type BooleansStringNumber = [...boolean[], string, number];
  • Related