Skip to content

Instantly share code, notes, and snippets.

@shyndman
Created November 27, 2024 03:18
Show Gist options
  • Select an option

  • Save shyndman/8f3dbb71d1dc3cc7c0c31eafb32e940f to your computer and use it in GitHub Desktop.

Select an option

Save shyndman/8f3dbb71d1dc3cc7c0c31eafb32e940f to your computer and use it in GitHub Desktop.
type PromiseOrUndefined = Promise<{}>|undefined;
class PromiseHoldingType<T extends PromiseOrUndefined> {
private _value: T;
constructor(value: T) {
this._value = value;
}
get value() {
return this._value;
}
isHoldingPromise(): this is PromiseHoldingType<Promise<{}>> {
return this._value instanceof Promise;
}
}
main().then(() => console.log("done"));
function main() {
const hasAPromise = new PromiseHoldingType(Promise.resolve({}));
const hasNoPromise = new PromiseHoldingType(undefined);
console.log("Guard on promise-holding type");
guardDemonstration(hasAPromise);
console.log("Guard on undefined holding type");
guardDemonstration(hasNoPromise);
}
function guardDemonstration(t: PromiseHoldingType<PromiseOrUndefined>) {
if (t.isHoldingPromise()) {
t.value.then(() => {}); // This is a-OK
} else {
t.value.then(() => {}); // This is an error, because value is still possibly undefined
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment