我可以在函数声明中使用现有的类型/接口吗?

时间:2019-11-27 09:14:37

标签: typescript

我想对功能组件使用React的类型定义,如下所示:

const SearchItem: React.FC<ISearchItemProps> = props => {}

SearchItem.name // ''

要将SearchItem命名为函数,我可以这样做:

const SearchItem: React.FC<ISearchItemProps> = function SearchItem(props) {}

SearchItem.name // 'SearchItem'

但这需要重复名称。

是否可以在函数声明中指定类型?例如:

function SearchItem/* React.FC<ISearchItemProps> */(props) {}

2 个答案:

答案 0 :(得分:1)

我认为您将不得不复制某物,因为TypeScript doesn't currently let you annotate a function statement with a type of the whole function (see microsoft/TypeScript#22063)。相反,您必须分别注释参数和返回类型。以下是使用标准ParametersReturnType实用程序类型时可能遇到的最糟糕的情况:

type RFC = React.FC<ISearchItemProps>;
function SearchItem(...args: Parameters<RFC>): ReturnType<RFC> {
    return null!; // or whatever it's supposed to return
}

console.log(SearchItem.name) // SearchItem

这可能比您原来的const SearchItem:... = function SearchItem(...)语法差,所以我建议您坚持使用。

希望有所帮助;祝你好运!

Link to code

答案 1 :(得分:-2)

有一个简单的方法,您只需要这样:

function SearchItem(props): React.FC<ISearchItemProps> {}

这意味着您的函数将具有React.FC<ISearchItemProps>类型的返回值