I have this Dir type alias that is a set of 8 cardinal directions, used as an enum:
type Dir = "N" | "NE" | "E" | "SE" | "S" | "SW" | "W" | "NW";
and I have a class Dirs that contains static members for only these values, as well as some utility methods on Dir:
class Dirs {
public static readonly N: Dir = "N";
public static readonly NE: Dir = "NE";
public static readonly E: Dir = "E";
public static readonly SE: Dir = "SE";
public static readonly S: Dir = "S";
public static readonly SW: Dir = "SW";
public static readonly W: Dir = "W";
public static readonly NW: Dir = "NW";
public static unitOffset(dir: Dir): MetroPosition {
// ...
}
public static opposite(dir: Dir): Dir {
// ...
}
}
Then, I can use them like this:
Dirs.unitOffset(Dirs.opposite(Dirs.N))
However, I want to change it to chained methods like this, for ergonomics:
Dirs.N.opposite().unitOffset()
In Rust, this is simple (disregarding the different actual values):
enum Dir {N,NE,E,SE,S,SW,W,NW}
impl Dir {
unitOffset(self) -> MetroPosition {
// ...
}
opposite(self) -> Self {
// ...
}
}
// usage
Dir::N.opposite().unitOffset()
Is there a way to give methods to a type alias?
Dirs.Nas string liketypeof Dirs.N === 'string'? You cannot attach methods to a specific pure JS string