简体   繁体   English

如何在 TypeScript 中将 function 类型声明为参数

[英]How to declare a function type as a parameter in TypeScript

I have a setState function in React that I would like to pass in to another function as a parameter.我在 React 中有一个 setState function,我想将它作为参数传递给另一个 function。 I was wondering how I can define this in TypeScript without using the "any" as the type:我想知道如何在不使用“any”作为类型的情况下在 TypeScript 中定义它:

So far it looks like this:到目前为止,它看起来像这样:

export const keyDownHandler = (event: React.KeyboardEvent, buttonDate: number, setShowCalendar: any): void => {
// stuff happening
setShowCalendar(false)
}

The type of a React state setter from useState is React.Dispatch<React.SetStateAction<stateType>> .来自useState的 React state 设置器的类型是React.Dispatch<React.SetStateAction<stateType>> In your case, it looks like the state type is boolean , so:在您的情况下,看起来 state 类型是boolean ,所以:

export const keyDownHandler = (event: React.KeyboardEvent, buttonDate: number, setShowCalendar: React.Dispatch<React.SetStateAction<boolean>>): void => {
    // stuff happening
    setShowCalendar(false);
};

You can see this in index.d.ts in @types/react , or in a decent IDE (VSCode for instance), you can see it by hovering your mouse over the state setter:您可以在@types/reactindex.d.ts中看到这一点,或者在一个不错的 IDE(例如 VSCode)中看到它,您可以通过将鼠标悬停在 state 设置器上来查看它:

状态设置器上的光标显示带有 const setShowCalendar 的弹出窗口:React.Dispatch<React.SetStateAction<boolean>>

In VSCode, hovering over setShowCalendar shows this popup:在 VSCode 中,将鼠标悬停在setShowCalendar上会显示此弹出窗口:

const setShowCalendar: React.Dispatch<React.SetStateAction<boolean>>

You could use the type definition like this.您可以像这样使用类型定义。

setShowCalendar: React.Dispatch<React.SetStateAction<boolean>>

I think the easiest solution would be (b: boolean) => void , but if you want the full type, you can use React.Dispatch<React.SetStateAction<boolean>> .我认为最简单的解决方案是(b: boolean) => void ,但如果你想要完整的类型,你可以使用React.Dispatch<React.SetStateAction<boolean>>

You can use a function type for this.您可以为此使用 function 类型。 For example, a function that takes a boolean and returns nothing would be something like:例如,采用 boolean 并没有返回任何内容的 function 将类似于:

const setShowCalendar = (value: boolean) => {
   ... 
   logic
   ...
}

setShowCalendar's type would be let setShowCalendar: (value: boolean) => void; setShowCalendar 的类型是let setShowCalendar: (value: boolean) => void; The type looks almost like the function itself, except for the fact that the body is missing.该类型看起来几乎像 function 本身,除了身体缺失的事实。

Look up the types you're consuming and replace it in the above example Type Declaration.在上面的示例类型声明中查找您正在使用的类型并将其替换。

You can read more about this here: https://www.typescriptlang.org/docs/handbook/functions.html#function-types您可以在此处阅读更多相关信息: https://www.typescriptlang.org/docs/handbook/functions.html#function-types

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM