简体   繁体   中英

How to define a type for a module inside the module itself?

Say I have a typescript file, named hello-service.ts :

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

In some cases, we want the type of this module. We can refer it in another ts file like this:

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

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

But I want to know, if is it possible to define such a type inside the hello-service.ts file itself?

For now, I can only achieve this by specifying every function, and which is quite boring:

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

Is there any simpler solution?

You can refer to the type of an import as typeof import('./hello-service.ts') . This will for sure work from outside the module. I have never used it from within a module, but from what I tried it works as expected even if it is a bit recursive:

// ./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()

Titian's answer can be further simplified:

hello.ts

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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