Issue
I have this type:
type PropsWithoutButton = { prop1: any };
type PropsWithButton = PropsWithoutButton & {
showButton: boolean;
onButtonPress: () => void;
}
type Props = PropsWithoutButton | PropsWithButton
Whenever trying to access showButton Typescript is throwing
Property 'showButton' does not exist on type 'PropsWithChildren<Props>'.
for example in a React component
const MyComponent: React.FC<Props> = ({
prop1,
showButton,
onButtonPress,
}) => ...
What's the error here and how can it be solved?
Solution
Typescript will resolve to the narrowest definition of a union (read unions as "or", e.g. TypeA | TypeB - "TypeA or TypeB"). Props, when used as a function parameter or class property, will resolve to { prop1: any } because tsc doesn't know what the real-time value passed to your component will be (i.e. if you pass something of type PropsWithoutButton, then showButton indeed does not exist).
Solutions
You may want something closer to this:
type Props = PropsWithoutButton & Partial<PropsWithButton>;
Note that this will make both additional props in PropsWithButton optional. If you want all or nothing you can use a function to assert a type (a.k.a. type guard):
function hasButton(p: Props) : p is PropsWithButton {
return 'showButton' in p && 'onButtonPress' in p;
}
Alternatively, you can check its type inline using in, e.g.
function bar(p: Props) {
if ('onButtonPress' in p) {
console.log(p.showButton); // no error here!
}
}
Here is a working example of this.
Answered By - Connor Low
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.