Skip to content

Instantly share code, notes, and snippets.

@NeutralAngel
Last active April 3, 2020 02:35
Show Gist options
  • Save NeutralAngel/0638dd384d8ec57201f2f01c3aebd788 to your computer and use it in GitHub Desktop.
Save NeutralAngel/0638dd384d8ec57201f2f01c3aebd788 to your computer and use it in GitHub Desktop.
type Freezable = {
unfreezable: never;
};
type Frozen<T extends Freezable> = T & {
frozen: true;
};
function assertFreezable(thing: unknown): asserts thing is Freezable {
if (!thing || (thing as Freezable).unfreezable) {
throw new Error(`Can't freeze that! ❄️`);
}
}
function freeze<T extends Freezable>(toFreeze: T): Frozen<T> {
assertFreezable(toFreeze);
(toFreeze as Frozen<T>).frozen = true;
return toFreeze as Frozen<T>;
}
const thing = {};
const frozenThing = freeze(thing); //Argument of type '{}' is not assignable to parameter of type 'Freezable'.
//Property 'unfreezable' is missing in type '{}' but required in type 'Freezable'.ts(2345)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment