javascript - 仅通过接口 TypeScript 键入函数的参数
问题描述
如何使用接口在下面键入函数的参数并保持它们干净(没有 Typescript)?
// external file
export interface TSomeFunctionArgs {
someKey: string
// also here should be a type for a function
}
// main file
import { TSomeFunctionArgs } from "pathToFile"
const someFunction = (args: TSomeFunctionArgs) => {
// ... function's logic
}
someFunction({ someKey: "some string" }, someAnotherFunction)
在我的示例中,我传递了两个参数,第一个是具有特定键值对的对象,第二个是函数(可以是任何函数)。
我如何在上面的界面中描述它?
解决方案
在这种情况下,您可以使用泛型,代码将是这样的:
interface TSomeFunctionArgs {
someKey: string
}
const someFunction = <U, T>(args: U, callback: T) => {
// ... function's logic
}
function someAnotherFunction() {}
// With generics you can give the type of the two parameters when you use it.
someFunction<TSomeFunctionArgs, () => void>({ someKey: "some string" }, someAnotherFunction)
推荐阅读
- c++ - C++/CLI 包装器不能使用来自本机 C++ dll 的向量
- javascript - 使用 vue 和 laravel 导入 Excel
- spring - 依次获取ParallelStream().parallel()数据
- maven - 在 Jenkins 构建期间在 Maven 中添加第三方依赖项的问题 - ODM
- msbuild - Azure DevOps 将 sqlproj 构建到 $(Build.ArtifactStagingDirectory)
- javascript - 如何使用变量进行推送?
- javascript - 如何在 HTML5 中播放多个音轨视频
- jenkins-pipeline - Jenkins管道阶段基于if条件在另一个阶段内
- c# - 如何获取表中分配的值
- javascript - 如何在地图中使用 react useRef 定位 DOM