Skip to content

Instantly share code, notes, and snippets.

@GoNZooo
Created December 24, 2018 21:48
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GoNZooo/243b23702df1fae38c966ae18832c690 to your computer and use it in GitHub Desktop.
Save GoNZooo/243b23702df1fae38c966ae18832c690 to your computer and use it in GitHub Desktop.
Phantom type variant in TypeScript
interface PlainText extends String {
__plaintext__: never
}
interface Base64Encoded extends String {
__base64Encoded__: never
}
interface Encrypted extends String {
__encrypted__: never
}
export const text = (s: string): PlainText => <PlainText><any>s;
export const base64Encode = (s: PlainText): Base64Encoded => {
return <Base64Encoded><any>atob(s.toString());
};
export const logBase64Encoded = (s: Base64Encoded): void => {
console.log(s);
};
export const sendOverNetwork = (s: Encrypted): void => {
// Dummy implementation
return;
};
export const usage = () => {
const plainText = text("Some text here");
const base64Encoded = base64Encode(plainText);
logBase64Encoded(base64Encoded);
// logBase64Encoded(plainText);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment