Created
November 27, 2024 03:18
-
-
Save shyndman/8f3dbb71d1dc3cc7c0c31eafb32e940f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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