How do I limit to only 2 number index signature class in TypeScript

Viewed 112

After googling for a while I can't find the right answer for me.

I want to declare a class that has a number index that only allows 0 and 1 number keys.

This is what I have so far:

class TupleWrapperClass{
   [values:number]

   constructor(value1: number, value2: number) {
       this[0] = value1;
       this[1] = value2;
   }
}

The idea is that this class represents a numeric tuple [number,number] and can only store 2 numbers. The problem I have is that it allows adding more than 2 elements:

let t = new TupleWrapperClass(0,3);
console.log(t[0]); // Output: 0
console.log(t[1]); // Output: 3
console.log(t[2]); // Output: undefined
t[2] = 7
console.log(t[2]); // Output: 7

I've read some answers where they define a type and the indexer, this seems to work

type Index = 0 | 1
type TupleWrapperType = { [k in Index]?: number }

BUT, I can't do a type check:

let t: TuppleWrapperType = { 0: 2, 1: 5 };
if(typeof t === TuppleWrapperType){} // Fails.

I've read a lot about custom types and why we can't check their type at runetime, that's why I switched to creating a custom class, since that do let me do a type check:

let t = new TupleWrapperClass(0,3);
if(t instanceof TuppleWrapperClass){} // All good

How do I limit my TuppleWrapperClass to only 2 indexes?

1 Answers

How about this one, declare the type in class before instantiation

class TupleWrapperClass{
   0: number;
   1: number;
   constructor(value1: number, value2: number) {
       this[0] = value1;
       this[1] = value2;
   }
}

let t = new TupleWrapperClass(0,3);

console.log(t[0]); // OK
console.log(t[1]); // OK
console.log(t[2]); // Type Error
Related