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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With