ElementProps, ElementConfig, "component props with defaultProps"
Now that TypeScript infers the external Props API for a Component with defaultProps, it would be helpful to add a type that returns the inferred props from a component. Flow accomplishes this with "React.ElementConfig".
class Test extends React.Component<{ foo: string, bar: number }> {
static defaultProps = {
foo: 'baz',
}
render() {
...
}
}
type TestProps = React.ElementConfig<Test>; // { foo?: string, bar: number }
My suggestion meets these guidelines:
You are looking for:
type TestProps = JSX.LibraryManagedAttributes<typeof Test, Test["props"]>;
which is what the TypeScript compiler is in fact using.
Would be nice to put that in the React .d.ts file for consistency
It also would be nice if TypeScript would automatically detect the type of defaultProps
class Test extends React.Component<{ foo: string, bar: number }> {
static defaultProps = {
bar: 'baz', <-- Error, Type 'string' is not assignable to type 'number'.
}
render() {
...
}
}
So we don't have to declare defaultProps as Partial<{ foo: string, bar: number }> or something like that.
(Sorry, if this should be an issue on its own I will gladly create it)
@cheeZery I don't understand the example. You have declared that the bar prop is a number but are setting a default that is a string?
Yeah, exactly, and that's the bug I would like TypeScript to detect :-) Sorry, that I didn't made that clear! At the moment you can set whatever key value pairs you want in defaultProps. TypeScript should know that keys of the declared Props interface are allowed here. Or am I missing something why this shouldn't be the case?
@cheeZery Yes, please file a new issue as this is unrelated to the current issue.
Is there any plan to add JSX.LibraryManagedAttributes<typeof T, T["props"]> into d.ts for React?
Most helpful comment
You are looking for:
which is what the TypeScript compiler is in fact using.