michael michael - 1 year ago 136
TypeScript Question

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

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

Answer Source

Typescript doesn't allow runtime type checking of interfaces. Instead, you can use your 3rd method by defining Coordinate as a class.

class Coordinate {
    longitude: number;
    latitude: number;

    constructor(long, lat) {
        this.longitude = long;
        this.latitude = lat;
let gps3 = new Coordinate(1,2);

if(gps3 instanceof Coordinate) // true

Also, typescript is intended to enforce static typing to otherwise dynamically typed javascript. But your method 2 doesn't necessarily limit the size of the array to 2 elements and gps2[10] is still a valid argument (although it's value would be of type any).

For readability, I would recommend using the method mentioned above in my answer.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download