Can I declare custom number types in TypeScript?

Can I somehow declare custom room types? For example. I would like to have a type UnixMsDate

and UnixSDate

, and I would like TS to help always distinguish and eliminate ambiguity between the two for me, that is, I never mix them up accidentally. Though they can convert between (and to / from) explicitly.

I tried type UnixMsDate = number

and it compiles, but it seems to be just a changeable alias for the number.

I am looking for something, perhaps somehow?

+3


source to share


1 answer


Using enums

enum UnixMsDate { }
enum UnixSDate { }

let date1: UnixMsDate;
let date2: UnixSDate;

date1 = date2; // Type 'UnixSDate' is not assignable to type 'UnixMsDate'.

function foo(x: UnixMsDate) { }
foo(date2); // Argument of type 'UnixSDate' is not assignable to type 'UnixMsDate'.

// All the below work.
date1 = +new Date();
date1 += 22;
console.log(date1 + date2);
date1 = 3.14159;
x1 = +x2;
x1 = Number(x2);
foo(+x2);

      

Alternative approach using intersection types

You can accomplish the same thing using intersection types:



type A = number & { _A: void; };
type B = number & { _B: void; };

      

This works almost identically, except that you will need to specify when assigning:

let a: A = <A>222;

      

It still doesn't get in the way of adding two types of numbers together. Here's more details on this hack.

+5


source







All Articles