繁体   English   中英

如何为模块内部的模块定义类型?

[英]How to define a type for a module inside the module itself?

假设我有一个名为hello-service.ts的打字稿文件:

export function hello1() { ... }
export function hello2() { ... }
export function hello3() { ... }

在某些情况下,我们需要此模块的类型。 我们可以在另一个ts文件中引用它,如下所示:

import * as helloService from './hello-service.ts';

function getHelloModule(): typeof helloService {
  return hello;
}

但我想知道,如果是可以定义里面这种类型的hello-service.ts文件本身?

现在,我只能通过指定每个函数来实现这一点,而且非常无聊:

export type HelloServiceType = {
   hello1: typeof hello1,
   hello2: typeof hello2,
   hello3: typeof hello3
}

有没有更简单的解决方案?

您可以将导入类型称为typeof import('./hello-service.ts') 这肯定会从模块外部开始工作。 我从来没有在一个模块中使用过它,但是从我尝试的它开始工作就像预期的那样,即使它有点递归:

// ./hello-service.ts
export function hello1() {  }
export function hello2() {  }
export function hello3() {  }


declare var exports: Self;
type Self = typeof import('./hello-service') 
export let self: Self = exports;

// usage.ts

import * as hello from './hello-service'
hello.self.hello1()

提香的答案可以进一步简化:

hello.ts

export function hello1() { return 1 }
export function hello2() { return 1 }
export function hello3() { return 1 }

export type TypeOfThisModule = typeof import ('./hello');

暂无
暂无

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

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