[英]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.