Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript Duck Typing, Want Strong Static Typing

TypeScript uses compile time (static) duck typing.

I am a fan of extending primitive types to prevent incorrect substitution. For example, I like to give a credit card number variable a credit card number type, rather than integer. I recently tried doing this in TypeScript with a pair of interfaces extending String, and found out that they freely substitute for one another (and that string substitutes for both).

I really would like to get compile time nominal typing. Any ideas?

like image 476
Eric Avatar asked Mar 26 '14 23:03

Eric


1 Answers

Please consider the following question:

Atomic type discrimination (nominal atomic types) in TypeScript

With it's example:

export type Kilos<T> = T & { readonly discriminator: unique symbol };
export type Pounds<T> = T & { readonly discriminator: unique symbol };

export interface MetricWeight {
    value: Kilos<number>
}

export interface ImperialWeight {
    value: Pounds<number>
}

const wm: MetricWeight = { value: 0 as Kilos<number> }
const wi: ImperialWeight = { value: 0 as Pounds<number> }

wm.value = wi.value;                  // Gives compiler error
wi.value = wi.value * 2;              // Gives compiler error
wm.value = wi.value * 2;              // Gives compiler error
const we: MetricWeight = { value: 0 } // Gives compiler error
like image 200
Lu4 Avatar answered Oct 05 '22 12:10

Lu4