Generic components with higher order components - reactjs

I'd like to give my React component props a generic type but this is being lost when I wrap it in a higher order component (material-ui) how do I pass along the required information?
type Props<T> = {
data: Array<T>;
}
class MyComponent<T> extends React.Component<Props<T>> {
const StyledComponent = withStyles(styles)(MyComponent)
Using <StyledComponent<myType gives an error as it doesn't know about the generic.

My bet is to annotate your new component like this:
const StyledComponent: <T>(props: OuterProps<T>) => JSX.Element = withStyles(styles)(MyComponent) ;
Mind you probably need to differentiate OuterProps and InnerProps, see below example I made for reference:
https://stackblitz.com/edit/hoc-generics
Hope that helps!

Related

Type of inputRef - TypeScript

I have a React component that accepts as props an inputRef
My Interface
interface Props extends WithStyles<typeof styles> {
body: text
inputRef?: any // I am not sure which TypeScript type I should use
}
My component
const MyComponent = ({
classes,
body,
inputRef
}: Props) => {
<TextField
body={body}
inputRef={inputRef}
/>
}
I am not sure which TypeScript type should I use for inputRef. I currently declare it as any but I want the right type.
I tried to use React.createRef<TextInput>() but I get the error: Namespace 'React' has no exported member 'createRef'
I have as types version: "#types/react": "^16.9.21"
Here is how I figure that out. When I create a reference to an element:
const wrapperRef = useRef<HTMLDivElement>(null);
I hover over the variable wrapperRef in VSCode to see what type it is. In this case I see:
const wrapperRef: RefObject<HTMLDivElement>
So, what you want to pass is RefObject<HTMLDivElement>.
Now if you do want an ElementRef, go ahead and use that (I'm not sure what kind of ref you are trying to pass). When you look at documentation or the actual type file you will see <T>. This is a Typescript Generic. It allows you to pass a type to the type declaration. Here is some documentation on it with many examples.

Strictly typing React higher order component which consumes properties with TypeScript

I'm trying to type some higher order React components which are more complex than only injecting properties. These HOCs must be able to:
receive properties that are not (or only optionally) forwarded to the wrapped component
provide some new properties to the wrapped component
take additional arguments when they are created
From what I can tell, this means we must have three types:
The properties the HOC provides to the wrapped component
The properties the HOC uses, but which the wrapped component not necessarily cares about
The properties of the wrapped component that the HOC doesn't care about
I have the following code that works, but I can't find a way to avoid the any cast when passing the props on to the wrapped component:
import React, { ComponentType } from 'react';
// Props of the wrapped component without the props provided by the HOC
type StrictWrappedProps<WrappedProps, InjectedProps> = Omit<
WrappedProps,
keyof InjectedProps
>;
type WrappedComponent<WrappedProps, InjectedProps> = ComponentType<
WrappedProps & InjectedProps
>;
type HOCType<WrappedProps, InjectedProps, OwnProps> = ComponentType<
OwnProps & StrictWrappedProps<WrappedProps, InjectedProps>
>;
type LengthifyOwnProps = {
name: string;
};
type LengthifyInjectedProps = {
length: number;
};
export const lengthify = <WrappedProps extends {}>(
Wrapped: WrappedComponent<WrappedProps, LengthifyInjectedProps>,
multiplier: number
): HOCType<WrappedProps, LengthifyInjectedProps, LengthifyOwnProps> => ({
name,
...props
}) => {
const length = name.length * multiplier;
return <Wrapped {...props as any} length={length} />;
};
Here is an example usage of that HOC:
const myComp = ({ bool, length }: { bool: boolean; length: number }) => (
<p>
Bool is: {bool}. Length is: {length}
</p>
);
const EnhancedMyComp = lengthify(myComp, 2);
const usage = () => <EnhancedMyComp bool={true} name="Hello" />;
The any cast is a small workaround, but I would like to find the strict way of typing this.
The React TypeScript cheat sheet on HOCs links to this bug in the TypeScript repo, but it seems to be more or less solved, and only relates to HOCs that inject properties.
Other questions here on StackOverflow also seem to to be about injecting properties, or confusion about the ComponentType type.

Typing antd form.create when component uses a generic type

I am having trouble properly typing a functional component that is wrapped in Form.create() that contains a generic.
Here is a sample of the functional component
interface IProps<T> extends FormComponentProps {
left: T;
right: T;
}
const SampleComponent = <T extends object>(props: IProps<T>): JSX.Element =>
{ leaving this out for simplicity };
export default Form.create()(SampleComponent);
When I try and use this component it complains that the props left and right do not exist, which makes sense since I can't figure out how to pass the generic type through.
For components that do not have a generic type I know to do Form.create<Props>(Component) but I am not sure how to properly pass along that generic type. Any help would be greatly appreciated.
You can use FunctionComponent which accepts a type argument, then declare the generic type (with whatever constraints, such as extends object) you want for your props in the prop interface like you're currently doing. Then you can pass whatever generic you're using as a parameter into the generic OF the generic for your component type. This will type your props automatically, so there's no need to declare them explicitly as your prop type. For example:
interface IProps<T extends object> extends FormComponentProps {
left: T;
right: T;
}
const SampleComponent: FunctionComponent<IProps<MyGenericType>> = ({ left, right }) => {
return <div/>
}
Where MyGenericType is the type of left and right which also extends the object type.
you need to change the last line as a reference from https://ant.design/components/form/#Using-in-TypeScript
Form.create<IProps>()(SampleForm);

React Component children typecheck with typescript

Here is the scenario:
I have a custom component:
class MyComponent extends React.Component {
render () {
return (
<SuperComponent>
<SubComponent1 /> // <- valid child
</SuperComponent>
)
}
class MyComponent extends React.Component {
render () {
return (
<SuperComponent>
<SubComponent2 /> // <- No! It's not right shape
</SuperComponent>
)
}
and the referenced SuperComponent and SubComponent1 are:
interface superPropsType = {
children: ReactElement<subPropsType1>
}
class SuperComponent extends React.Component<superPropsType> { ... }
interface subPropsType1 = {
name: string
}
class SubComponent1 extends React.Component<subPropsType1> { ... }
interface subPropsType2 = {
title: string
}
class SubComponent2 extends React.Component<subPropsType2> { ... }
I want SubComponent1 to be the only valid child of SuperComponent, that is, I wish typescript can throw an error if I place <SubComponent2 /> or Other types as child of <SuperComponent>
It seems like typescript only check that the child of should have the type of ReactElement, but ts doesn't check the shape of props of that child (which is subPropsType1), that is, if I place a string or number as child of SuperComponent, ts will complaints that type requirement doesn't meet, but if I place any jsx tag here(which will transpiled to ReactElement), ts will keep silent
Any idea ? And if any configs are required to post here, please don't hesitate to ask
Really appreciate any idea and solution
As of TypeScript 3.1, all JSX elements are hard-coded to have the JSX.Element type, so there's no way to accept certain JSX elements and not others. If you wanted that kind of checking, you would have to give up the JSX syntax, define your own element factory function that wraps React.createElement but returns different element types for different component types, and write calls to that factory function manually.
There is an open suggestion, which might be implemented as soon as TypeScript 3.2 (to be released in late November 2018), for TypeScript to assign types to JSX elements based on the actual return type of the factory function for the given component type. If that gets implemented, you'll be able to define your own factory function that wraps React.createElement and specify it with the jsxFactory compiler option, and you'll get the additional type information. Or maybe #types/react will even change so that React.createElement provides richer type information, if that can be done without harmful consequences to projects that don't care about the functionality; we'll have to wait and see.
I would probably declare SuperPropsType.children as:
children: React.ReactElement<SubPropsType1> | React.ReactElement<SubPropsType1>[];
To account for the possibility of having both a single and multiple children.
In any case, as pointed out already, that won't work as expected.
What you could do instead is declare a prop, let's say subComponentProps: SubPropsType1[], to pass down the props you need to create those SubComponent1s, rather than their JSX, and render them inside SuperComponent:
interface SuperPropsType {
children?: never;
subComponentProps?: SubPropsType1[];
}
...
const SuperComponent: React.FC<SuperPropsType> = ({ subComponentProps }) => {
return (
...
{ subComponentProps.map(props => <SubComponent1 key={ ... } { ...props } />) }
...
);
};

Typescript with React - use HOC on a generic component class

I have a generic React component, say like this one:
class Foo<T> extends React.Component<FooProps<T>, FooState> {
constructor(props: FooProps<T>) {
super(props);
render() {
return <p> The result is {SomeGenericFunction<T>()}</p>;
}
}
I also have a HOC that looks similar to this one (but is less pointless):
export const withTd =
<T extends WithTdProps>(TableElement: React.ComponentType<T>): React.SFC<T> =>
(props: T) => <td><TableElement {...props}/></td>;
But when I use a component like this:
const FooWithTd = withTd(Foo);
There is no way to pass the type argument, as you can do neither withTd(Foo<T>), nor can you do FooWithTd, the type is always wrong.
What is the proper way to do that?
EDIT: The problem is that I want to be able to have something like <FooWithTd<number> {...someprops}/> later on, as I don't know the desired type for T in the HOC.
You can wrap your component which is created from a HOC into another component. It would look something like this:
class FooWithTd<T> extends React.Component<SomeType<T>> {
private Container: React.Component<SomeType<T> & HOCResultType>;
constructor(props:SomeType<T>){
super(props);
this.Container = withTd(Foo<T>);
}
render() {
return <this.Container {...this.props} />;
}
}
Remember, you probably don't want the HOC inside your render function because it means that the component will be recreated every each render.
Thanks for asking this question. I just figured out a way to specify a type parameter to a component after wrapping it with an HOC and I thought I'd share.
import React from 'react';
import withStyles from '#material-ui/core/styles/withStyles';
import { RemoveProps } from '../helpers/typings';
const styles = {
// blah
};
interface Props<T> {
classes: any;
items: T[];
getDisplayName: (t: T) => string;
getKey: (t: T) => string;
renderItem: (t: T) => React.ReactNode;
}
class GenericComponent<T> extends React.Component<Props<T>, State> {
render() {
const { classes, items, getKey, getDisplayName, renderItem } = this.props;
return (
<div className={classes.root}>
{items.map(item => (
<div className={classes.item} key={getKey(item)}>
<div>{getDisplayName(item)}</div>
<div>{renderItem(item)}</div>
</div>
))}
</div>
);
}
}
// 👇 create a `type` helper to that output the external props _after_ wrapping it
type ExternalProps<T> = RemoveProps<Props<T>, 'classes'>;
export default withStyles(
styles
)(GenericComponent) as <T extends any>(props: ExternalProps<T>) => any;
// 👆 cast the wrapped component as a function that takes
// in a type parameter so we can use that type
// parameter in `ExternalProps<T>`
The main idea is to cast the wrapped component as a function that takes in a type parameter (e.g. T) and use that type parameter to derive the external props after the component has been wrapped.
If you do this, then you can specify a type parameter when using the wrapped version of GenericComponent e.g.:
<GenericComponent<string> {/*...*/} />
Hopefully the code is explanatory enough for those who still have this problem. In general though, I consider this relatively advanced typescript usage and it's probably easier to use any instead of a generic parameter in the props
Workaround: simple case
If your component's type parameter is used only for passing it to props, and users of the component do not expect it having any functionality beyond just passing props and rendering, you can explicitly hard-cast the result of your hoc(...args)(Component) to React's functional component type, like this:
import React, {ReactElement} from 'react';
class MyComponent<T> extends React.Component<MyProps<T>> { /*...*/ }
const kindaFixed = myHoc(...args)(MyComponent) as unknown as <T>(props: MyProps<T>) => ReactElement;
Workaround: more complex and with some runtime costs
You can use fabric-like function, supposed here:
class MyComponent<T> extends React.Component<MyProps<T>> { /*...*/ }
export default function MyComponentFabric<T>() {
return hoc(...args)(MyComponent as new(props: MyProps<T>) => MyComponent<T>);
}
This one will require you to create new version of wrapped component for each type you use it with:
import MyComponentFabric from '...whenever';
const MyComponentSpecificToStrings = MyComponentFabric<string>();
It will allow you to access all public instance fields and methods of your component.
Summary
I faced this issue when tried to use connect from react-redux on my ExampleGenericComponent<T>. Unfortunatelly, it cannot be fixed properly until TypeScript will support HKT, and any HOC you use will update its typings respecting this feature.
There is possibly no correct solution (at least for now) for usages beyond just rendering, when you need to access component instance fields and methods. By 'correct' I mean 'without ugly explicit typecasts', and 'with no runtime cost'.
One thing you can try is to split your class-component into two components, one that will be used with HOC, and other that will provide fields and methods that you need.
Just stumbled upon this as well and thought I'd share what I came up with in the end.
Building on what #rico-kahler provided, my approach mapped to your code would be
export const FooWithTd = withTd(Foo) as <T>(props: FooProps<T>) => React.ReactElement<FooProps<T>>;
which you can then use like this
export class Bar extends React.Component<{}> {
public render() {
return (
<FooWithTd<number> />
);
}
}
In my case, I have defaultProps as well and I inject props by ways of another HOC, the more complete solution would look like this:
type DefaultProps = "a" | "b";
type InjectedProps = "classes" | "theme";
type WithTdProps<T> = Omit<FooProps<T>, DefaultProps | InjectedProps> & Partial<FooProps<T> & { children: React.ReactNode }>;
export const FooWithTd = withTd(Foo) as <T>(props: WithTdProps<T>) => React.ReactElement<WithTdProps<T>>;
EDIT:
After some changes to your code, it was only a wrong constraint T in your withTd function.
// I needed to change the constraint on T, but you may adapt with your own needs
export const withTd = <T extends FooProps<WithTdProps>>(
TableElement: React.ComponentType<T>
): React.SFC<T> => (props: T) => (
<td>
<TableElement {...props} />
</td>
)
// Explicitly typed constructor
// Removed after EDIT
//const FooW = Foo as new (props: FooProps<WithTdProps>) => Foo<WithTdProps>
// Inferred as React.StatelessComponent<FooProps<WithTdProps>>
const FooWithTd = withTd(Foo)
No longer relevant after EDIT :
You may find more information at this issue https://github.com/Microsoft/TypeScript/issues/3960

Resources