Skip to content

[Advanced] Request for props type example: "Props: One only if the other" #110

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
stephenkoo opened this issue Apr 26, 2019 · 7 comments
Closed
Labels
ADVANCED Advanced Cheatsheet

Comments

@stephenkoo
Copy link
Contributor

What cheatsheet is this about? (if applicable)
Advanced cheatsheet

What's your issue or idea?
Your prop type examples are awesome.

I'm keen to find an example that answers this question here - only allow prop B if prop A is passed to a component. 😄

@stephenkoo stephenkoo added the ADVANCED Advanced Cheatsheet label Apr 26, 2019
@swyxio
Copy link
Collaborator

swyxio commented Apr 27, 2019

probably try using function overloading. try it, if it doesn’t work, post what you tried.

@stephenkoo
Copy link
Contributor Author

Would it be done like this?

type CommonProps = {
  children: React.ReactNode;
}

type NoTruncateProps = CommonProps & {
  truncate?: false;
}

type TruncateProps = CommonProps & {
  truncate: true;
  expanded?: boolean;
}

function Typography(props: NoTruncateProps): JSX.Element;
function Typography(props: TruncateProps): JSX.Element;
function Typography({ children, as: Tag, truncate, ...otherProps }: NoTruncateProps | TruncateProps) {
  if (truncate) {
    return (<Tag truncate={truncate} expanded={otherProps.expanded} {...otherProps}>{children}</Tag>)
  }
  return (<Tag truncate={truncate}>{children}</Tag>)
}

@swyxio
Copy link
Collaborator

swyxio commented Apr 28, 2019

hmm. not sure you can do truncate ?: false like that. did it work?

edit: huh, TIL about boolean literals. yeah i think your thing works. wanna PR?

@stephenkoo
Copy link
Contributor Author

Let me test it first - my actual component is a bit more complex so I'll need to double-check if the above works.

@stephenkoo
Copy link
Contributor Author

PR (with some modifications to above code): #111

@swyxio
Copy link
Collaborator

swyxio commented May 2, 2019

very nice! thank you and i'm glad you figured it out! @allcontributors[bot] please add @stephenkoo for questions and examples

@allcontributors
Copy link
Contributor

@sw-yx

I've put up a pull request to add @stephenkoo! 🎉

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
ADVANCED Advanced Cheatsheet
Projects
None yet
Development

No branches or pull requests

2 participants