Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

typescript: any difference between number[] and [number,number]?

Tags:

typescript

I'm just learning Typescript and trying to understand best practices for types and interfaces. I am playing with an example using GPS coordinates and want to know if one approach is better than another.

let gps1 : number[];
let gps2 : [number, number]
interface Coordinate {
   0: number,
   1: number
}
let gps3 : Coordinate;

I suppose the bigger question is if there is a value in typing an array of fixed size & type. Because Typescript does not allow me to easily test if a value is of a certain type on runtime, correct? (i.e. unserialized from a JSON string)

gps3 = [1,3]
let check = gps3 instanceof Coordinate;  // doesn't work
like image 759
michael Avatar asked Jan 05 '23 10:01

michael


1 Answers

In your example gps1 is an array of numbers and gps2 is a tuple of two numbers:

Tuple types allow you to express an array where the type of a fixed number of elements is known, but need not be the same.

The reason that gps3 instanceof Coordinate does not work is that Coordinate is an interface and not an actual runtime type.
The compiler user that interface to type check your code, but it does not get translated into javascript.

You can create a type guard for that:

interface Coordinate {
   0: number,
   1: number
}

function isCoordinate(obj: any): obj is Coordinate {
    return obj instanceof Array && obj.length === 2 && typeof obj[0] === "number" && typeof obj[1] === "number";
}

let a;

if (isCoordinate(a)) {
    console.log(a[0]);
}
like image 129
Nitzan Tomer Avatar answered Jan 13 '23 10:01

Nitzan Tomer