簡體   English   中英

節點模塊打字稿類實例類型檢查

[英]Node Module Typescript Class instance Type Checking

目前,我的任務是從Vanilla JS創建節點模塊並將其移至打字稿。 我將它們重寫為類,添加了一些功能,編寫了舊式包裝和相應的Web Pack配置。 問題是這些模塊中的某些模塊是單例的,因此,我們不是要默認導出類,而是要默認導出類實例。 問題是我沒有使類型檢查正常工作:

import DebugJs from 'debug';
const test = (test: DebugJs) => {
    test.console('warn', 'does', 'respond', 'with a warning', test);
};

這里的問題是DebugJs無法識別為類型。 因此,目前我必須導入其他接口才能正確設置類型。

只是為了比較,這是我目前所做的:

import DebugJs, { DebugJsInterface } from 'debug';
const test = (test: DebugJsInterface) => {
    test.console('warn', 'does', 'respond', 'with a warning', test);
};

我嘗試了命名空間和模塊聲明,但是老實說,作為一個對節點模塊創建完全陌生並且對打字稿非常陌生的人,我真的不知道我在做什么。

這是我當前的index.d.ts文件設置

import DebugJs from './src/debugJsModule';
import {DebugLevels} from "./src/types/types";

export interface DebugJsInterface {
    levels:DebugLevels;
    enabled:boolean;
    level:number;
    console(...arguments: any): void;
    enableDebug(): void;
    disableDebug(): void;
    setLevel(level:number): void;
}

export interface Module {
    DebugJs: DebugJsInterface;
}

export default DebugJs;
declare module 'debug';

在這里,DebugJsInterface被定義為解決方法。 我還感到有些困惑,因為我認為idnex.d.ts應該只包含類型信息。 但是,如果我不從此處導出類實例,則模塊導入不會被正確識別為類。

這是我的debugJsModule包裝器,它返回一個類實例:

import DebugJs from './class/DebugJs';
import { DebugLevels } from 'debug/src/types/types';

const DebugJsInstance: DebugJs = new DebugJs();

export default DebugJsInstance;

該類本身被簡單地定義為一個類,並作為默認導出導出

 class DebugJs { ... } 

明確地說,從功能上講一切正常,所有我想弄清楚如何通過使用相同的導入名稱(在本例中為DebugJs)來擁有合適的importet類實例類型,而不必依賴於額外的importet接口,解決方法。

我現在不知道這種模式是否適合您,但是我通常通過將類和單例放置在同一文件中,並將單例導出為默認值並將類導出為命名導出來實現:

class DebugJs {
  // code
}

const debug = new DebugJs();

export default debug;
export {DebugJs};

然后在客戶端中,如果我導入單例:

import debug from '.../path';

debug.format().log().whatever(); // typings and intellisense works fine. debug will be recognised as DebugJs instance.

而且,如果您需要與單例無關的DebugJs的新實例, DebugJs可以:

import {DebugJs} from '.../path';

const debug = new DebugJs(); // typing and intellisense will work

我非常確定這會起作用,因為我經常使用此模式。

但是我不正確地知道為什么您的設置不起作用。 我不知道是否對類型使用默認導出,或者將其與單例重新導出結合使用可能會導致您的問題。

這個代碼片段實際上沒有什么意義:

import DebugJs from 'debug';
const test = (test: DebugJs) => {
    test.console('warn', 'does', 'respond', 'with a warning', test);
};

在這里,您不是在請求DebugJs的實例,而是在告訴打字稿期望an instance of an instance of DebugJs

問題是,我認為這里沒有任何意義。 為什么要導入某事物的實例然后立即不使用它?

無論如何,有可能,它只需要以下語法:

const test = (test: typeof DebugJs) => {
    test.console('warn', 'does', 'respond', 'with a warning', test);
};

您可能會想要:

  1. 不導入實例,而是導入DebugJsInterface 那就是您應該用於類型防護的內容。
  2. 或者:不需要將其作為參數。

范例1:

const test = (test: DebugJsInterface) => {
    test.console('warn', 'does', 'respond', 'with a warning', test);
};

范例2:

const test = () => {
    DebugJs.console('warn', 'does', 'respond', 'with a warning', test);
};

我懷疑你想要以上之一

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM