Skip to content

Instantly share code, notes, and snippets.

@gaku-sei
Created January 12, 2018 21:48
Show Gist options
  • Save gaku-sei/9da57722d95421cefa739309cad90b1b to your computer and use it in GitHub Desktop.
Save gaku-sei/9da57722d95421cefa739309cad90b1b to your computer and use it in GitHub Desktop.
type NewType<Name extends string, Type> = Type & {
readonly "": Type;
};
function to<T extends NewType<string, U>, U = T[""]>(x: U): T {
return x as T;
}
type Size = NewType<"Size", number>;
function logSize(size: Size): void {
console.log(size);
}
// const s = to<Size>("42"); // Fails
// const s = to<Size>(); // Fails
// const s = to<Size, string>("42"); // Fails
const s = to<Size>(42); // Works !
// logSize(42) // Fails
logSize(s) // Works !
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment