我想在基于打字稿的项目中在自己的文件中定义几个接口,从中我将实现用于生产的类以及用于测试的模拟。但是,我不知道什么是正确的语法。我已经找到了很多有关声明接口和实现接口的教程,但是它们都在同一个文件中实现了接口和派生类的简单实现,而这在现实世界中并不是很真实。导出和导入接口的正确方法是什么?
Answers:
您需要从定义的文件中导出接口,然后将其导入到要使用的位置。
在IfcSampleInterface.ts
:
export interface IfcSampleInterface {
key: string;
value: string;
}
在 SampleInterface.ts
import { IfcSampleInterface } from './IfcSampleInterface';
let sampleVar: IfcSampleInterface;
module.ts
和module.d.ts
在同一个文件夹中,编译器会跳过module.d.ts
文件,所以你的声明将不被考虑。重命名d.ts
文件或将其移动到另一个文件夹。如果您有合适的模块,这种方法很好,但是如果您想在模块之间共享类型,最好使用import .. from ..
。
d.ts
到我的react项目中,但是我仍然需要导入接口。
在不分散多个导出的情况下,可以将它们分组在一个export {}
块中(在这种情况下,不应声明任何文件default
类型):
// interfaces.ts
interface IWords {
[key: string]: string;
}
interface INumbers {
[key: string]: number;
}
interface IBooleans {
[key: string]: boolean;
}
interface IValues {
[key: string]: string | number;
}
interface IStructures {
[key: string]: INumbers | IBooleans | IValues;
}
export {
// not exporting IWords | INumbers
IBooleans,
IValues,
IStructures,
}
import { IBooleans, IValues, IStructures } from 'interfaces';
const flags: IBooleans = { read: true, write: false, delete: false };
const userFile: IValues = { user: 1, username: 'One', file: 'types.txt' };
const userContext: IStructure = {
file: userFile,
permissions: flags,
counts: { views: 3, writes: 1 } // => INumbers (lint: try to remove IValues from IStructures)
};
您需要将接口导出到定义的文件中,并将它们导入到使用它们的文件中。有关示例,请参见此链接。
则
interface X{
...
}
export default X
ts
import X from "./x.ts"
// You can use X now
有关更多信息,请参见https://www.typescriptlang.org/docs/handbook/modules.html