pavel_karoukin
pavel_karoukin

Reputation: 286

How to extend basic type in typescript?

I had an instance where two properties both had to of "number" and I used one instead of another on an accident. Nothing complained and it took a while to debug these.

I wonder if it is possible to extend basic types to make sure that when I try to assign, for example, the value of type Age to a variable with type Score (both being numbers tired)?

EDIT: Sorry for the original question not having a code sample. Nurbol Alpysbayev correctly interpreted my question and his code sample indeed represents what I wanted to see happening:

type Score = number;
type Age = number;

let score: Score = 999;
let age: Age = 45;

score = age; // I want to have this line to throw an error

Upvotes: 2

Views: 111

Answers (1)

Nurbol Alpysbayev
Nurbol Alpysbayev

Reputation: 21851

The quality of the question could be far better, but I think I understood it.

I believe you did something like this:

type Score = number
type Age = number

let score: Score = 999
let age: Age = 45

score = age // no errors (and it confused you)

Now the answer to your question is: both Age and Score are type aliases of the same type, which is number. The names are just for convenience, that's why they are called aliases in the first place.

So you are using type aliases for a wrong task. If you need to differentiate types, then you have to use interfaces like this:

interface Score {type: 'score', value: number}
interface Age {type: 'age', value: number}

let score: Score = {type: 'score', value: 999}
let age: Age = {type: 'age', value: 45}

score = age // error

However you should know that for data representing Score and Age, you should just leave type number without over-engineering them.

Upvotes: 3

Related Questions