【问题标题】:How to import the derived type of an exported function in TypeScript如何在 TypeScript 中导入导出函数的派生类型
【发布时间】:2015-12-23 09:15:39
【问题描述】:

我有两个文件 myFunction.tsindex.ts

  • myFunction.ts 导出这样的函数:
export default (param1: string) => { return true }
  • index.ts 像这样导入该函数:
import myFunction from './myFunction'

然后我想像这样使用来自myFunction 的类型:

function bla(aFn: myFunction) {
  aFn('hello')
}

但是,编译器给了我一个cannot find name myFunction

如何获取导出函数的类型?

作为一种解决方法,您可以像这样为函数创建和导出类型:

export type MyFunctionType = (param1: string) => boolean
export default (param1: string) => { return true; }

然后像这样导入:

import myFunction, { MyFunctionType } from './myFunction';

function bla(myFunction: MyFunctionType) {
  myFunction('hello')
}

但是你会指定类型信息两次,这是我想避免的......

【问题讨论】:

  • 这行得通吗? (在 a.ts 中)const a = (param1: string) => { return true; }; export default a;
  • 我试过的是function a(param1: string) { return true; }; export default a;,但也没有用...
  • 哦,我知道问题出在哪里。我会尽快添加答案。

标签: typescript


【解决方案1】:

Louy 在某种程度上是对的。需要使用 typeof 来获取类型信息:

import myFunction from './myFunction'

function bla(myFunction: typeof myFunction) {
  myFunction('hello')
}

【讨论】:

    【解决方案2】:

    我认为你在混合类型和默认参数之类的东西。

    a 的类型是 Functiona 本身不是一个类型。默认参数可以这样指定:

    function bla(aFn = a) {
      aFn('hello');
    }
    

    如果您需要 aFn 具有类似于 a 的签名,则必须指定该签名或为其创建一个接口。

    function bla(aFn: (s: string) => boolean) {
      aFn('hello');
    }
    

    或者……

    interface a { (s: string): boolean; }
    function bla(aFn: a) {
      aFn('hello');
    }
    

    【讨论】:

    • 实际上你需要使用typeof a,正如我在我的回答中发布的那样。谢谢你,因为你给我指出了正确的方向;)
    • 不要使用typeof。这没有意义,通常是一种不好的做法。你为什么要创建一个函数来读取它的签名?而是创建一个接口。
    猜你喜欢
    • 1970-01-01
    • 2019-04-30
    • 1970-01-01
    • 2018-04-27
    • 1970-01-01
    • 2021-10-23
    • 1970-01-01
    • 1970-01-01
    • 2016-03-12
    相关资源
    最近更新 更多