[英]Use import/require in TypeScript to get interface declarations
[英]Cannot use "interface" declarations from TypeScript in JS (React Native tests)
我有一個 ReactNative 應用程序,我正在嘗試使用 Jest 編寫測試。 我的測試需要使用來自本機組件(react-native-nfc-manager)的類和我需要的 class 聲明如下
export interface TagEvent {
ndefMessage: NdefRecord[];
maxSize?: number;
type?: string;
techTypes?: string[];
id?: number[];
}
如果我嘗試直接使用這個定義,比如
const event = new TagEvent();
我收到這個錯誤
TypeError:_reactNativeNfcManager.default 不是構造函數
我來自 Java 世界,所以我想我自己 - 當然它不能實例化一個接口,它需要一個 class 所以我為此接口編寫了一個測試實例:
class TestTagEvent implements TagEvent {
ndefMessage: NdefRecord[] = []
maxSize?: number;
type?: string;
techTypes?: string[];
id?: number[];
}
但問題似乎有所不同,因為它也不起作用:
TypeError:_TestTagEvent.TestTagEvent 不是構造函數
我錯過了什么?
您不能使用接口構造 object。 接口只是一組屬性,可用於定義變量的必需/可用屬性。
要使用接口初始化變量,您需要執行以下操作:
const eventVar: TagEvent;
如果要將 TagEvent 用作可實例化的 object,則需要將其定義為 class,而不是接口。 像這樣,其中TagEventProps
是您定義的TagEvent
接口:
class TagEvent {
constructor(props: TagEventProps) {
this.ndefMesssage = props.nDefMessage;
//etc...
}
}
在進一步的實驗之后,通過向 class 添加“導出”來解決問題。 誠然,最初的錯誤描述絕對不符合根本原因。
導出 class TestTagEvent 實現 TagEvent {
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.