Skip to content

Commit 3d0f919

Browse files
Basarat Ali SyedBasarat Ali Syed
authored andcommitted
promise safety
1 parent 924975f commit 3d0f919

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

SUMMARY.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,7 @@
8181
* [Build Toggles](docs/tips/build-toggles.md)
8282
* [Barrel](docs/tips/barrel.md)
8383
* [Create Arrays](docs/tips/create-arrays.md)
84+
* [Promise Safety](docs/tips/promise-safety.md)
8485
* [StyleGuide](docs/styleguide/styleguide.md)
8586
* [Common Errors](docs/errors/main.md)
8687
* [TypeScript Compiler Internals](docs/compiler/overview.md)

docs/tips/promise-safety.md

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
## Promise Safety
2+
The following code doesn't error by default:
3+
4+
```ts
5+
declare let both: Promise<{ type: string, value: string; }>;
6+
declare let valueOnly: Promise<{ value: string }>;
7+
declare let typeOnly: Promise<{ type: string }>;
8+
declare let empty: Promise<{}>;
9+
10+
// Why no error?
11+
both = valueOnly;
12+
both = typeOnly;
13+
both = empty;
14+
```
15+
16+
This is because `Promise<T>` doesn't use the type `T` as a member and only in functions. The function type compatability rules allow the promise's to be compatible in this case.
17+
18+
### Fix
19+
20+
You can add the following to increase `Promise` type safety (do it globally):
21+
22+
```ts
23+
interface Promise<T>{
24+
_ensureTypeSafety: T;
25+
}
26+
```
27+
28+
And now the following errors:
29+
30+
```ts
31+
declare let both: Promise<{ type: string, value: string; }>;
32+
declare let valueOnly: Promise<{ value: string }>;
33+
declare let typeOnly: Promise<{ type: string }>;
34+
declare let empty: Promise<{}>;
35+
36+
// Error!
37+
both = valueOnly; // property type is missing
38+
both = typeOnly; // property value is missing
39+
both = empty; // property missing
40+
```

0 commit comments

Comments
 (0)