![](/img/trans.png)
[英]Why is a property on my Typescript-defined class showing up as undefined?
[英]Typescript seeing property as undefined, when it is defined
打字稿不斷抱怨並拋出錯誤,
Property 'tableData' is missing in type '{ children?: ReactNode; }' but required in type '{ tableData: TableData; }'
這是我的代碼:
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')
}
};
我在這里做錯了什么?
遵循FunctionComponent
的定義,它是一個泛型類型,它期望 props 作為第一個參數提供,否則默認為空對象,稍后與children
prop 結合,所以你最終只會得到children
prop。
要修復它,您只需將定義傳遞給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
}
}) => {
// ...
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.