Skip to content

Instantly share code, notes, and snippets.

View alessioprestileo's full-sized avatar

Alessio Prestileo alessioprestileo

View GitHub Profile
@alessioprestileo
alessioprestileo / calculations.ts
Last active April 23, 2021 15:13
Type-safe calculations using different units of measurement
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);
@alessioprestileo
alessioprestileo / units-of-measurement.ts
Last active April 23, 2021 14:32
Type definitions and constructors for units of measurement
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}
@alessioprestileo
alessioprestileo / construct-fstring.ts
Created April 23, 2021 13:01
Attempts to construct a value of type FString
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;
@alessioprestileo
alessioprestileo / tagged-intersection-def.ts
Created April 23, 2021 12:40
Definition of tagged interesction according to TypeScript's handbook for functional programmers
type FString = string & { __compileTimeOnly: any };