How to use antd.Form.create in typescript?

Kennir picture Kennir · Jul 4, 2017 · Viewed 13.2k times · Source

I have a login form created by Form.create(), but I can't pass any props to this form from parent component, compiler always notify a error like

error TS2339: Property 'loading' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes<Compone
nt<{}, ComponentState>> & Readonly<{ childr...'.

LoginForm.tsx

import * as React from 'react';
import { Form } from 'antd';
import { WrappedFormUtils } from 'antd/lib/form/Form';

interface Props {
    form: WrappedFormUtils;
    loading: boolean;
    username?: string;
}

class LoginForm extends React.Component<Props, {}> {
    render() {
        const { loading } = this.props;
        return (<div>form {loading ? 'true' : 'false'}</div>);
     }
}

export default Form.create()(LoginForm);

LoginPage.tsx

import LoginForm from './components/loginForm';

const loginPage: React.SFC<Props> = (props) => {
     return (
         <div>
              <LoginForm loading={true}/>
                         ^ error here!
         </div>
     );
 };

My antd version is 2.11.2


Finally I found a solution

class LoginForm extends React.Component<Props & {form:     WrappedFormUtils}, State> {
  render() {
    const { loading } = this.props;
    return (<div>form {loading ? 'true' : 'false'}</div>);
  }
}

export default Form.create<Props>()(LoginForm);

Answer

AmazingTurtle picture AmazingTurtle · Nov 9, 2017
  1. Import the FormComponentProps

    import {FormComponentProps} from 'antd/lib/form/Form';
    
  2. Then have your component

    interface YourProps {
        test: string;
    }        
    
    class YourComponent extends React.Component<YourProps & FormComponentProps> {
        constructor(props: YourProps & FormComponentProps) {
            super(props);
            ...
        }
    }
    
  3. Then export the class using Form.create()

    export default Form.create<YourProps>()(YourComponent);
    

    The generic argument on Form.create casts the result to a React ComponentClass with YourProps - without FormComponentProps, because these are being injected through the Form.create wrapper component.