If your components Props interface extends another interface, defaultProps still doesn't work in TS3
gausie opened this issue · 12 comments
ok what do you recommend i put in the cheatsheet?
have you reported this as a bug? (is this a bug? i think it is?)
just try :) good luck
Do you have a code example for this? I would also open this as an issue in the DefinitelyTyped repo instead so the other React types maintainers can take a look.
I guess it goes like
type ComponentProps<T> = T extends React.ComponentType<infer P> | React.Component<infer P>
? JSX.LibraryManagedAttributes<T, P>
: never;
interface IProps {
name: string;
}
interface IDefaultProps {
age: number;
}
const GreetComponent = ({ name, age }: IProps & IDefaultProps) => (
<div>{`Hello, my name is ${name}, ${age}`}</div>
);
const defaultProps: IDefaultProps = {
age: 25,
};
GreetComponent.defaultProps = defaultProps;
// later
const TestComponent = (props: ComponentProps<typeof GreetComponent>) => {
return (
<div> <h1 /> </div>
);
};
const el = <TestComponent name="foo" />;
thanks for the input @infctr! i dont quite see the point of TestComponent.
- if i replace your impl of ComponentProps with the official one
React.ComponentProps
, i see that TestComponent errors because of the missingage
default prop. - if i then add
TestComponent.defaultProps = defaultProps;
it typechecks.
this seems correct behavior.
@gausie, can we please see an example that you expect to work? otherwise its very hard to discuss.
@sw-yx My point is (and that's my understanding of @gausie problem)
type Props = React.ComponentProps(typeof GreetComponent) // all props are required
type Props = ComponentProps<typeof GreetComponent> // using helper, defaulted props are optional
Extracting props with JSX.LibraryManagedAttributes
is more in line with the old practice marking default props as optional on an interface like interface Props extends Partial<DefaultProps> { /* ... */ }
and using it later.
Consdider this
interface Props extends ComponentProps<typeof GreetComponent> {
title: string;
}
const TestComponent = ({ title, ...props }: Props) => {
return (
<>
<h1>{title}</h1>
<GreetComponent {...props} />
</>
);
};
// age is optional on an inner component's props interface
const el = <TestComponent name="Johnny 5" title="foo" />;
Just thought it was worth mentioning as it was not immediately obvious
That's correct. There are valid use cases for extracting both the inner props of a component, or the apparent props (with JSX.LibraryManagedAttributes
). The built-in React types only take care of the first case.
hoo boy. ok. thank you
This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions!