簡體   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