首页 > 解决方案 > 仅通过接口 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)

在我的示例中,我传递了两个参数,第一个是具有特定键值对的对象,第二个是函数(可以是任何函数)。

我如何在上面的界面中描述它?

标签: javascripttypescript

解决方案


在这种情况下,您可以使用泛型,代码将是这样的:

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)

推荐阅读