如何在模块内部定义一个类型?

3

假设我有一个 TypeScript 文件,名为 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
}

有没有更简单的解决方案?
2个回答

1
你可以使用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()

1

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

hello.ts

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接