This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {Feet, Meters, Measurement, toMeasurement} from './units-of-measurement'; | |
function area<T extends Measurement>(width: T, height: T): T { | |
return toMeasurement<T>(width * height); | |
} | |
const widthFeet = toMeasurement<Feet>(4); | |
const heightFeet = toMeasurement<Feet>(5); | |
const areaFeet = area<Feet>(widthFeet, heightFeet); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export type Meters = number & {__tagMeters: never}; | |
export type Feet = number & {__tagFeet: never}; | |
export type Measurement = Meters | Feet; | |
export function toMeasurement<T extends Measurement>(val: number): T {return val as T} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type FString = string & { __compileTimeOnly: any }; | |
const failure1: FString = 'hello world'; // Error: Type 'string' is not assignable to type '{ __compileTimeOnly: any; }'. | |
const failure2: FString = { __compileTimeOnly: 'whatever' }; // Error: Type '{ __compileTimeOnly: string; }' is not assignable to type 'string'. | |
const success1: FString = 'hello world' as FString; | |
const success2: FString = { __compileTimeOnly: 'whatever' } as FString; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type FString = string & { __compileTimeOnly: any }; |