You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
## Props: Can Optionally Pass One Only If the Other Is Passed
460
+
461
+
Say you want a Text component that gets truncated if `truncate` prop is passed but expands to show the full text when `expanded` prop is passed (e.g. when the user clicks the text).
462
+
463
+
You want to allow `expanded` to be passed only if `truncate` is also passed, because there is no use for `expanded` if the text is not truncated.
464
+
465
+
You can do this by function overloads:
466
+
467
+
```tsx
468
+
import React from "react";
469
+
470
+
type CommonProps = {
471
+
children: React.ReactNode;
472
+
as: "p"|"span"|"h1"|"h2"|"h3"|"h4"|"h5"|"h6";
473
+
};
474
+
475
+
type NoTruncateProps = CommonProps & {
476
+
truncate?:false;
477
+
};
478
+
479
+
type TruncateProps = CommonProps & {
480
+
truncate: true;
481
+
expanded?:boolean;
482
+
};
483
+
484
+
// Type guard
485
+
const isTruncateProps = (
486
+
props: NoTruncateProps | TruncateProps
487
+
): props is TruncateProps => !!props.truncate;
488
+
489
+
// Function overloads to accept both prop types NoTruncateProps & TruncateProps
490
+
function Text(props: NoTruncateProps): JSX.Element;
491
+
function Text(props: TruncateProps): JSX.Element;
492
+
function Text(props: NoTruncateProps | TruncateProps) {
<Texttruncateexpanded>truncate-able but expanded</Text> {/* works */}
527
+
528
+
{/* TS error: Property 'truncate' is missing in type '{ children: string; expanded: true; }' but required in type 'Pick<TruncateProps, "expanded" | "children" | "truncate">'} */}
529
+
<Textexpanded>truncate-able but expanded</Text>
530
+
</>
531
+
);
532
+
```
533
+
458
534
## Omit attribute from a type
459
535
460
536
Sometimes when intersecting types, we want to define our own version of an attribute. For example, I want my component to have a `label`, but the type I am intersecting with also has a `label` attribute. Here's how to extract that out:
0 commit comments