Skip to content

Commit 9b29018

Browse files
committed
More twoslashing
1 parent a5c5410 commit 9b29018

File tree

2 files changed

+124
-97
lines changed

2 files changed

+124
-97
lines changed

book-content/chapters/05-unions-literals-and-narrowing.md

Lines changed: 27 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -639,12 +639,19 @@ By adding this error condition, we can be sure that we will never reach any subs
639639

640640
If we hover over `appElement` after the `if` statement, we can see that TypeScript now knows that `appElement` is an `HTMLElement` - it's no longer `null`. This means our test also now passes:
641641

642-
```tsx
643-
console.log(appElement);
642+
```ts twoslash
643+
import { Equal, Expect } from "@total-typescript/helpers";
644644

645-
// hovering over `appElement` shows:
645+
const appElement = document.getElementById("app");
646646

647-
const appElement: HTMLElement;
647+
if (!appElement) {
648+
throw new Error("Could not find app element");
649+
}
650+
651+
// ---cut---
652+
653+
console.log(appElement);
654+
// ^?
648655

649656
type Test = Expect<Equal<typeof appElement, HTMLElement>>; // passes
650657
```
@@ -1310,14 +1317,29 @@ type State =
13101317

13111318
Now, if we hover over `state.error` in the `renderUI` function, we can see that TypeScript knows that `state.error` is a `string`:
13121319

1313-
```typescript
1320+
```ts twoslash
1321+
type State =
1322+
| {
1323+
status: "loading";
1324+
}
1325+
| {
1326+
status: "error";
1327+
error: string;
1328+
}
1329+
| {
1330+
status: "success";
1331+
data: string;
1332+
};
1333+
1334+
// ---cut---
13141335
const renderUI = (state: State) => {
13151336
if (state.status === "loading") {
13161337
return "Loading...";
13171338
}
13181339

13191340
if (state.status === "error") {
13201341
return `Error: ${state.error.toUpperCase()}`;
1342+
// ^?
13211343
}
13221344

13231345
if (state.status === "success") {
@@ -1724,7 +1746,6 @@ Even though the `status` and `value` variables are separate, TypeScript keeps tr
17241746

17251747
```typescript
17261748
// hovering over `status` shows
1727-
17281749
const status: "error" | "success";
17291750
```
17301751

0 commit comments

Comments
 (0)