Wizek
Wizek

Reputation: 5003

Can I declare custom number types in TypeScript?

Can I somehow declare custom number types? E.g. I'd like to have a UnixMsDate and a UnixSDate type, and I'd like if TS could help to always distinguish and disambiguate between these two for me, meaning that I never accidentally mix them up. While being able to convert between them (and to/from number) explicitly.

I tried type UnixMsDate = number and it compiles, but it seems to be just an interchangeable alias to number.

Is what I am looking for possible somehow?

Upvotes: 7

Views: 1899

Answers (1)

user663031
user663031

Reputation:

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 cast when assigning:

let a: A = <A>222;

It still does not prevent adding numbers of the two types together. Here is more information on this hack.

Upvotes: 9

Related Questions