Reputation: 198238
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?
Upvotes: 3
Views: 245
Reputation: 25790
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');
Upvotes: 1
Reputation: 249636
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()
Upvotes: 1