简体   繁体   中英

Typescript error on prop types of stateless React Component

In my project, someone wrote the following lines of code, which result in a Typescript error:

export const MaskedField = asField(({ fieldState, fieldApi, ...props }) => 
    {
        const {value} = fieldState;
        const {setValue, setTouched} = fieldApi;
        const {
            forwardedRef,
            guide,
            icon,
            initialValue,
            keepCharPositions,
            maskRegEx,
            onBlur,
            onChange,
            placeholder,
            placeholderChar,
            ...rest
        } = props;
    }
}

First of all, Lint gives me a trailing comma error, but when I place one after props , I get another Typescript error that spreadoperators can't have a trailing comma.

Most importantly, I'm having errors on the fields of the const {...} = props variable, telling me Property '...' does not exist on type '{ children?: ReactNode; }'. Property '...' does not exist on type '{ children?: ReactNode; }'.

Any idea on how to fix this quickly?

If you want to use TypeScript then you need to provide type information so TS can do it's type checking thing.

At the moment you haven't provided any information about the props type, so it only knows it has an optional children prop. That's why it says: Property '...' does not exist on type '{ children?: ReactNode; }'. Property '...' does not exist on type '{ children?: ReactNode; }'.

Here's an example from the excellent React Redux TypeScript Guide site by Piotrek Witek:

import * as React from 'react';

export interface SFCCounterProps {
  label: string;
  count: number;
  onIncrement: () => any;
}

export const SFCCounter: React.SFC<SFCCounterProps> = (props) => {
  const { label, count, onIncrement } = props;

  const handleIncrement = () => { onIncrement(); };

  return (
    <div>
      <span>{label}: {count} </span>
      <button type="button" onClick={handleIncrement}>
        {`Increment`}
      </button>
    </div>
  );
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM