【问题标题】:Type function's arguments only via Interface TypeScript仅通过接口 TypeScript 键入函数的参数
【发布时间】:2020-07-17 19:14:15
【问题描述】:

如何使用接口在下面键入函数的参数并保持它们干净(没有 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)

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

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

【问题讨论】:

    标签: javascript typescript


    【解决方案1】:

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

    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)
    

    【讨论】:

    • 我正在寻找一种只输入参数而不是整个函数的方法。因此它可以通过导出/导入应用于其他功能
    • @Andrew 在这种情况下,您可以使用两个泛型。我编辑代码。
    • 这不是回答关于keep it clean 的部分。我需要将() =&gt; void 移到外面并通过接口/类型定义它们
    • 在这种情况下,您可以将对象作为参数而不是各种参数传递,否则您不能使用接口输入参数
    猜你喜欢
    • 2018-03-21
    • 2019-06-15
    • 2018-11-01
    • 2022-11-29
    • 2021-07-28
    • 1970-01-01
    • 2018-09-15
    • 1970-01-01
    • 2019-06-08
    相关资源
    最近更新 更多