I am kinda a newbie with TypeScript, and I am using it on a real project along with React.
I saw a post where the writter indicates two ways of declare conditional props in React using Typescript.
The writer indicates two ways to declare conditional props in React using TypeScript.
I tried the solution using generics (because I want to approach it that way), and I did not get TypeScript warning me about the type that should be the prop called "level" after checking if the authenticated prop was true.
Here’s the code:
type Props<T extends boolean> = {
authenticated: T;
level: T extends true ? 'basic' | 'admin' : 'guest'
};
const User = <T extends boolean>(props: Props<T>) => {
if (props.authenticated) {
return <>Profile ({props.level})</>; }
return <>{props.level}</>
};
2
Answers
Why would you expect a warning? Your usage of
level
in both cases is valid, it’s astring
unless if I am missing your pointThis is what you have now:
You should define two different user types and then create a discriminated union:
Here is how you can apply the types above to your component: