简体   繁体   English

如何在 TypeScript 中导入导出函数的派生类型

[英]How to import the derived type of an exported function in TypeScript

I have two files myFunction.ts and index.ts .我有两个文件myFunction.tsindex.ts

  • myFunction.ts exports a function like so: myFunction.ts导出如下函数:
export default (param1: string) => { return true }
  • index.ts imports that function like so: index.ts导入函数如下:
import myFunction from './myFunction'

and then I want to use the typings from myFunction like so:然后我想像这样使用来自myFunction

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

However, the compiler gives me a cannot find name myFunction .但是,编译器给了我一个cannot find name myFunction

How do I get the typings for the exported function?如何获取导出函数的类型?

As a workaround, you can create and export a type for the function like so:作为解决方法,您可以为函数创建和导出类型,如下所示:

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

And then import like so:然后像这样导入:

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

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

but then you'd be specifying the type information twice, which is something I would like to avoid...但是你会指定两次类型信息,这是我想避免的......

Louy was to some extend right.路易在某种程度上是对的。 You need to use typeof to get the type information:您需要使用 typeof 来获取类型信息:

import myFunction from './myFunction'

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

I think you're mixing types and default parameters or something.我认为您正在混合类型和默认参数或其他东西。

Type of a is Function .类型aFunction a is not a type by itself. a本身不是一种类型。 The default param can be specified like this:可以像这样指定默认参数:

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

If you instead need aFn to have a signature similar to a , you'll have to specifiy that signature or create an interface for it.如果您不是需要aFn有类似签名a ,你必须specifiy该签名或为它创建一个接口。

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

Or...或者...

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

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

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