newtype
TypeScript "" (TypeScript , , ) , . :
interface Height {
__brand: "height"
}
function height(inches: number): Height {
return inches as any;
}
function inches(height: Height): number {
return height as any;
}
interface Weight {
__brand: "weight"
}
function weight(pounds: number): Weight {
return pounds as any;
}
function pounds(weight: Weight): number {
return weight as any;
}
const h = height(12);
const w = weight(2000);
Height
Weight
(, ) . height()
Height
( number
a Height
), inches()
( Height
a number
), weight()
pounds()
- Weight
. - . JavaScript , , , , , :
const h = 12 as any as Height;
const w = 2000 as any as Weight;
, , Height
, Weight
. , newtype
, number
. , Height
Weight
number
( ), , , : +
number
, h
w
number
, h + w
. h
w
number
, h + h
. , TypeScript , . h + h
, h + w
, Height
Weight
number
s. add()
, , :
type Dimension = Height | Weight;
function add<D extends Dimension>(a: D, b: D): D {
return ((a as any) + (b as any)) as any;
}
add()
Height
Weight
. , , - Height | Weight
D
, , , :
function add(a: Height, b: Height): Height;
function add(a: Weight, b: Weight): Weight;
function add(a: any, b: any): any {
return a+b;
}
,
const twoH = add(h, h);
const twoW = add(w, w);
const blah = add(h, w);
, . measureScale()
Weight
:
declare function measureScale(): Weight;
var a = height(68);
var b = measureScale();
:
console.log(add(a,b));
console.log(add(a,a));
, ; !