Created
March 14, 2019 11:59
-
-
Save isthatcentered/b755a504d39407fb3f8ba49ca895e198 to your computer and use it in GitHub Desktop.
Typescript - Opaque type
This file contains 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 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