Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

// doSomethingToSegment.js

/** 
 * typedef {(string|number)[]} segment
 */
  
/**
 * @param {segment} seg input segment
 * @param {object} options
 */
function doSomethingToSegment(seg, options) {} 

Now the doSomethingToSegment() function will say that Math.round(someVar,3) is not ok because someVar is not ok with type string, or otherVar.toUpperCase() is not ok with type number.

So, how to define a custom type definition that satisfies this specific need?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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];
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading