Closed tikotzky closed 6 years ago
Hey @tikotzky thanks for the detailed error report, as a short term "fix" I'd suggest asserting the component created via withProps
to the correct type.
https://codesandbox.io/s/q39q1ljj19
If no one else has, I'll try and have a deeper look and see how this may be resolved on the weekend.
+1 running into the same problem
The relevant code for this issue is:
export interface GlamorousComponentFunctions<ExternalProps, Props> {
...
withProps: <DefaultProps extends object>(
props: DefaultProps,
) => GlamorousComponent<ExternalProps & Partial<DefaultProps>, Props>
}
where:
ExternalProps
are extra props that a component needs. In your expample it is H2Props
.
DefaultProps
are props that we provide with withProps
method. Those props should be opional in the returned component.
Props
are CSS props (not relevant in this case)
As we can see the props for the returned component are of type ExternalProps & Partial<DefaultProps>
. In the example it translates to:
H2Props & Partial<H2Props>
which gives {color: string} & {color?: string}
. This unfortunately is equal to { color: string }
as the stricter constraints take precedence which makes providing color
prop to GreenH2
a requirement. This of course doesn't express the behavior of the code where color
should be optional.
To fix this we need to make the props provided in DefaultProps
object optional. The way to do this is to exclude props in DefaultProps
from ExteralProps
. The proper type for the returned component should be:
GlamorousComponent<
Pick<ExternalProps, Diff<keyof ExternalProps, keyof DefaultProps>> &
Partial<DefaultProps>,
Props
>;
Diff
returns keys that are in ExternalProps
but not in DefaultProps
In 2.8 version of typescript we can also use built-in types instead of hacky Diff
:
GlamorousComponent<
Pick<ExternalProps, Exclude<keyof ExternalProps, keyof DefaultProps>> &
Partial<DefaultProps>,
Props
>;
This would be really nice.
This project is now in an unmaintained status. Please see the README for more information.
glamorous
version: 4.12.1glamor
version: 2.20.40react
version: 16.2.0typescript
version: 2.7.2Relevant code.
What you did: Created a component and then set default props using
withProps
What happened: The TS compiler still requires the props to be passed even though there are default props set
withProps
Reproduction:
https://codesandbox.io/s/z7y906l2p
Problem description: TS is requiring props which should be optional since defaults were set using
withProps
Suggested solution: Not sure...