Skip to content

Commit e773f0f

Browse files
Replace invalid props example
1 parent 608b33f commit e773f0f

File tree

1 file changed

+26
-11
lines changed

1 file changed

+26
-11
lines changed

docs/advanced/patterns_by_usecase.md

Lines changed: 26 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -709,23 +709,38 @@ const UsageComponent = () => (
709709

710710
[View in the TypeScript Playground](https://www.typescriptlang.org/play/?jsx=2#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgcilQ3wFgAoCmATzCTgAUcwBnARjgF44BvOTCBABccFjCjAAdgHM4AXwDcVWvSYRWAJi684AIxRQRYiTPlLK5TAFdJGYBElwAstQDCuSJKSSYACjDMLCJqrBwAPoyBGgCUvBRwcMCYcL4ARAIQqYmOAeossTzxCXAA9CVwuawAdPpQpeVIUDhQRQlEMFZQjgA8ACbAAG4AfDyVLFUZct0l-cPmCXJwSAA2LPSF5MX1FYETgtuNza1w7Z09syNjNQZTM4ND8-IUchRoDmJwAKosKNJI7uAHN4YCJkOgYFUAGKubS+WKcIYpIp9e7HbouAGeYH8QScdKCLIlIZojEeIE+PQGPG1QnEzbFHglABUcHRbjJXgpGTxGSytWpBlSRO2UgGKGWwF6cCZJRe9OmFwo0QUQA)
711711

712-
Further reading: [how to ban passing `{}` if you have a `NoFields` type.](http://www.javiercasas.com/articles/typescript-impossible-states-irrepresentable)
713-
714-
## Props: Must Pass Both
712+
## Props: Pass nothing or all
715713

716714
```tsx
717-
type OneOrAnother<T1, T2> =
718-
| (T1 & { [K in keyof T2]?: undefined })
719-
| (T2 & { [K in keyof T1]?: undefined });
715+
interface Nothing {
716+
[key: string]: never; // needed because an empty interface is equivalent to `{}`
717+
}
720718

721-
type Props = OneOrAnother<{ a: string; b: string }, {}>;
719+
interface All {
720+
a: string;
721+
b: string;
722+
}
722723

723-
const a: Props = { a: "a" }; // error
724-
const b: Props = { b: "b" }; // error
725-
const ab: Props = { a: "a", b: "b" }; // ok
724+
const NothingOrAll = (props: Nothing | All) => {
725+
if ("a" in props) {
726+
// `props` is of type `All`
727+
return <>{props.b}</>;
728+
}
729+
// `props` is of type `Nothing`
730+
return <>Nothing</>;
731+
};
732+
733+
const Component = () => (
734+
<>
735+
<NothingOrAll />
736+
<NothingOrAll a="" /> {/* error */}
737+
<NothingOrAll b="" /> {/* error */}
738+
<NothingOrAll a="" b="" />
739+
</>
740+
);
726741
```
727742

728-
Thanks [diegohaz](https://twitter.com/kentcdodds/status/1085655423611367426)
743+
Read more about [how to make invalid states irrepresentable](http://www.javiercasas.com/articles/typescript-impossible-states-irrepresentable).
729744

730745
## Props: Pass One ONLY IF the Other Is Passed
731746

0 commit comments

Comments
 (0)