Skip to content

Instantly share code, notes, and snippets.

@isthatcentered
Created March 14, 2019 11:59
Show Gist options
  • Save isthatcentered/b755a504d39407fb3f8ba49ca895e198 to your computer and use it in GitHub Desktop.
Save isthatcentered/b755a504d39407fb3f8ba49ca895e198 to your computer and use it in GitHub Desktop.
Typescript - Opaque type
export type Opaque<T, K> = K & { __TYPE__: T };
// Create a new opaque type
type WaffleId = Opaque<number, "waffledId">;
// This function now handles the knowledge of what a waffleId is, change will only happen there if needed
function makeWaffleId( number: number ): WaffleId
{
// ...do stuff
return (number as any) as WaffleId;
}
const willFail: WaffleId = 5 // Type "5" is not assignable to type "WaffleId"
const willWork: WaffleId = makeWaffleId( 5 )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment