UNPKG

1.38 kBTypeScriptView Raw
1/**
2Create an opaque type, which hides its internal details from the public, and can only be created by being used explicitly.
3
4The generic type parameter can be anything. It doesn't have to be an object.
5
6[Read more about opaque types.](https://codemix.com/opaque-types-in-javascript/)
7
8There have been several discussions about adding this feature to TypeScript via the `opaque type` operator, similar to how Flow does it. Unfortunately, nothing has (yet) moved forward:
9 - [Microsoft/TypeScript#15408](https://github.com/Microsoft/TypeScript/issues/15408)
10 - [Microsoft/TypeScript#15807](https://github.com/Microsoft/TypeScript/issues/15807)
11
12@example
13```
14import {Opaque} from 'type-fest';
15
16type AccountNumber = Opaque<number>;
17type AccountBalance = Opaque<number>;
18
19function createAccountNumber(): AccountNumber {
20 return 2 as AccountNumber;
21}
22
23function getMoneyForAccount(accountNumber: AccountNumber): AccountBalance {
24 return 4 as AccountBalance;
25}
26
27// This will compile successfully.
28getMoneyForAccount(createAccountNumber());
29
30// But this won't, because it has to be explicitly passed as an `AccountNumber` type.
31getMoneyForAccount(2);
32
33// You can use opaque values like they aren't opaque too.
34const accountNumber = createAccountNumber();
35
36// This will compile successfully.
37accountNumber + 2;
38```
39*/
40export type Opaque<Type> = Type & {readonly __opaque__: unique symbol};