看了网上很多 TypeScript 的 React 函数组件的写法,要么是不写返回类型,要么是给整个函数组件写上类型 React.FunctionComponent
。
函数组件是函数,函数不写返回类型总觉得不安心。
写 React.FunctionComponent
的话,有个隐式的 children,不喜欢。
用 vscode peek type definition 看了下,推断的返回类型是 JSX.Element,这是一个 extends React.ReactElement<any, any> 的 Interface,所以尝试写成了类似这样:
type HelloProps = { readonly name: string }
function Hello({ name }: HelloProps): ReactElement<HelloProps> {
return <button>Hello {name}!</button>
}
这样写可以编译。
但不确定是不是恰当的写法?