简体   繁体   中英

Typescript seeing property as undefined, when it is defined

Typescript keeps complaining and throwing the error,

Property 'tableData' is missing in type '{ children?: ReactNode; }' but required in type '{ tableData: TableData; }'

Here is my code:

import React, { FC } from 'react';

interface TableData  {
  someField: string;
  anotherField?: string;
  someFunction?: Function;
}

const Table: FC = ({
  tableData: {
    someField,
    anotherField,
    someFunction
  }
}: {
  tableData: TableData;
}) => {
  // ...
};

Table.defaultProps = {
  tableData: {
    someField: 'field1',
    anotherField: 'field2',
    someFunction: () =>
      console.log('Some function')
  }
};

What am I doing wrong here?

Following the definition of FunctionComponent it's a generic type which expects props to be provided as a first parameter, otherwise defaults to empty object which later gets combined with children prop so you will end up with children prop only.

To fix it you just need to pass definition to FC :

import React, { FC } from 'react';

interface TableData  {
  someField: string;
  anotherField?: string;
  someFunction?: Function;
}

interface Props {
  tableData: TableData
}

const Table: FC<Props> = ({
  tableData: {
    someField,
    anotherField,
    someFunction
  }
}) => {
  // ...
};

Typescript playground

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