如何在单独的文件中声明和导入typescript接口

时间:2022-09-25 12:06:55

I want to define several interfaces in their own file in my typescript-based project, from which I'll implement classes for production as well as mocks for testing. However, I can't figure out what the correct syntax is. I've found plenty of tutorials on declaring interfaces and implementing them, but they all have a trivial implementation of both the interface and derived classes in the same file, which isn't very real-world. What's the right way to export and import the interfaces?

我想在我的基于打字稿的项目中在他们自己的文件中定义几个接口,我将从中实现用于生产的类以及用于测试的模拟。但是,我无法弄清楚正确的语法是什么。我发现了许多关于声明接口和实现它们的教程,但它们都在同一个文件中有一个简单的接口和派生类实现,这不是很现实。导出和导入接口的正确方法是什么?

3 个解决方案

#1


28  

You need to export the interface from the file in which is defined and import it wherever you want to use it.

您需要从定义的文件中导出接口,并将其导入到您要使用它的任何位置。

IfcSampleInterface.ts

IfcSampleInterface.ts

export interface IfcSampleInterface {
   key: string;
   value: string;
}

SampleInterface.ts

SampleInterface.ts

import { IfcSampleInterface } from './IfcSampleInterface.ts';

let sampleVar: IfcSampleInterface;

#2


8  

Use definition (d.ts) files and namespaces, no need to import/export modules this way. DefinitelyTyped project has guidance and huge number of examples how to do it.

使用定义(d.ts)文件和命名空间,无需以这种方式导入/导出模块。 DefinitelyTyped项目有指导和大量的例子如何做。

#3


2  

You need to export the interfaces in the file the are defined in and import them in the files they are used in. See this link for examples.

您需要导出定义的文件中的接口,并将它们导入到它们所使用的文件中。有关示例,请参阅此链接。

x.ts

x.ts

interface X{
    ...
}
export default X

y.ts

y.ts

import X from "./x.ts"
// You can use X now

For more information see https://www.typescriptlang.org/docs/handbook/modules.html

有关更多信息,请参阅https://www.typescriptlang.org/docs/handbook/modules.html

#1


28  

You need to export the interface from the file in which is defined and import it wherever you want to use it.

您需要从定义的文件中导出接口,并将其导入到您要使用它的任何位置。

IfcSampleInterface.ts

IfcSampleInterface.ts

export interface IfcSampleInterface {
   key: string;
   value: string;
}

SampleInterface.ts

SampleInterface.ts

import { IfcSampleInterface } from './IfcSampleInterface.ts';

let sampleVar: IfcSampleInterface;

#2


8  

Use definition (d.ts) files and namespaces, no need to import/export modules this way. DefinitelyTyped project has guidance and huge number of examples how to do it.

使用定义(d.ts)文件和命名空间,无需以这种方式导入/导出模块。 DefinitelyTyped项目有指导和大量的例子如何做。

#3


2  

You need to export the interfaces in the file the are defined in and import them in the files they are used in. See this link for examples.

您需要导出定义的文件中的接口,并将它们导入到它们所使用的文件中。有关示例,请参阅此链接。

x.ts

x.ts

interface X{
    ...
}
export default X

y.ts

y.ts

import X from "./x.ts"
// You can use X now

For more information see https://www.typescriptlang.org/docs/handbook/modules.html

有关更多信息,请参阅https://www.typescriptlang.org/docs/handbook/modules.html