How can i type some possible states of a class instance?

Viewed 17

I'm new to typescript. I have a vector class and a type that only accepts 4 possible states of the vector.

class Vector{
  x:number = 0;
  y:number = 0;

  constructor(x:number, y:number){
    this.x = x;
    this.y = y;
  }
}

type DirectionVector = 
  {
    x: 1;
    y: 0;
  } | {
    x: -1;
    y: 0;
  } | {
    x: 0;
    y: 1;
  } | {
    x: 0; 
    y: -1;
  }

I want to be able to type some of my vectors so that they can only be from one of those 4 states

this is what i expected

const vec:DirectionVector = new Vector(5,3); //type error
const vec2:DirectionVector = new Vector(1,0); //good

and this is what i get

const vec2:DirectionVector = new Vector(1,0);
/*
Type 'Vector' is not assignable to type 'DirectionVector'.
  Type 'Vector' is not assignable to type '{ x: 0; y: -1; }'.
    Types of property 'x' are incompatible.
      Type 'number' is not assignable to type '0'
*/
0 Answers
Related