为什么这个箭头函数与具有相同签名的非箭头函数不一样?

Why does this arrow function not the same as the non-arrow function with the same signature?

我有两个具有相同签名的函数(据说),但从编译器的角度来看它们似乎并不相同:箭头函数中的 todosTodo[] 类型,而非箭头函数中的 todosany 类型。

我一定是漏掉了什么。

    interface TodoState {
      todos: Todo[]
    }

//no error
    const arrowFunc: React.FC<TodoState> = ({ todos }) => { }

//error: binding element 'todos' implicitly has an 'any' type.ts(7031)
    function nonArrow({ todos }): React.FC<TodoState> {}

const arrowFunc: React.FC<TodoState> = ({ todos }) => {}
//               ^ function type       ^ props        ^ function return value

这里声明了一个函数,该函数的类型符合React.FC<TodoState>。也就是说,功能组件接受像 TodoState 这样的道具,加上 children 属性 和 returns JSX。

function nonArrow({ todos }): React.FC<TodoState> {}
//                            ^ function return value

但这说明了一些不同的东西。 nonArrow 是一个没有 return JSX 的函数,它 return 是一个功能组件。

第一种形式将函数键入 React.FC<TodoState>,第二种形式将函数的 return 值键入 React.FC<TodoState>.


没有使用 function 关键字分配现有函数类型的语法。通常,如果您希望这样输入功能组件,您可以使用第一种形式。

但这只有在您需要 children 作为道具时才有用。否则,这个简单的构造对大多数功能组件都适用:

function MyFuncComp({ propName }: Props) {
  return <h1>{propName}</h1>
}

// called like this:
<MyFuncComp propName='foo'/>

大部分时间你需要输入的只是 props,然后 return 一些 JSX 和 Typescript+React 会为你解决剩下的问题。


或者如果您的组件需要 children,通常会这样做:

interface Props {
  propName: string
}

const MyFuncComp: React.FC<Props> = ({ propName, children }) => {
  return <div>
    <h1>{propName}</h1>
    {children}
  </div>
}

// called like this:
<MyFuncComp propName='foo'>
  <p>some children</p>
</MyFuncComp>

函数括号()后面提到的类型,表示return类型,而不是它自己的类型。

function YourComponentName():React.FC{} 表示此函数的return类型是功能组件。 而 const YourComponentName:React.FC{} 表示这个函数的类型,即函数组件。