Skip to content

Commit 626138d

Browse files
committed
add type narrowing examples
1 parent 8f0334c commit 626138d

File tree

3 files changed

+40
-0
lines changed

3 files changed

+40
-0
lines changed

README.md

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,36 @@ const response = await fetch("https://api.scryfall.com/sets");
3434
const sets: ScryfallList.Sets = await response.json();
3535
```
3636

37+
### Type narrowing on a card
38+
39+
```ts
40+
import { ScryfallCard, ScryfallLayout } from "@scryfall/api-types";
41+
42+
// This card might be of any type.
43+
// You cannot access `mysteryCard.card_faces`, because it might not have that property.
44+
const mysteryCard: ScryfallCard.Any = getCard();
45+
46+
// You can narrow by layout:
47+
if (mysteryCard.layout === ScryfallLayout.Transform) {
48+
// It's a transforming DFC!
49+
// You can access transform-specific fields in this scope, or assign it to a variable.
50+
const faces = anyCard.card_faces;
51+
const transform: ScryfallCard.Transform = mysteryCard;
52+
}
53+
54+
// You can also narrow by property:
55+
if ("card_faces" in anyCard) {
56+
// It's *some* kind of multi-faced card.
57+
// You can now access the card_faces property.
58+
// You'll need to do some further type narrowing to know more about what's in the card.
59+
const faces = anyCard.card_faces;
60+
const multifaced: ScryfallCard.AnyMultiFaced = anyCard;
61+
} else {
62+
const sfc: ScryfallCard.AnySingleFaced = anyCard;
63+
}
64+
65+
```
66+
3767
## Usage
3868

3969
Each type and enum exported by this library corresponds to a Scryfall API object and its values.
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
import { ScryfallCard } from "src";
2+
3+
const anyCard = {} as ScryfallCard.Any;
4+
5+
if ("card_faces" in anyCard) {
6+
const faces = anyCard.card_faces;
7+
const mfc: ScryfallCard.AnyMultiFaced = anyCard;
8+
} else {
9+
const sfc: ScryfallCard.AnySingleFaced = anyCard;
10+
}
File renamed without changes.

0 commit comments

Comments
 (0)