typescript 如何在单独的文件中声明和导入打字稿接口
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37263357/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to declare and import typescript interfaces in a separate file
提问by snort
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?
我想在我的基于打字稿的项目中的自己的文件中定义几个接口,从中我将实现用于生产的类以及用于测试的模拟。但是,我无法弄清楚正确的语法是什么。我找到了很多关于声明接口和实现它们的教程,但它们都在同一个文件中实现了接口和派生类,这不是很现实。导出和导入接口的正确方法是什么?
回答by Ajay
You need to export the interface from the file in which is defined and import it wherever you want to use it.
您需要从定义的文件中导出接口,然后将其导入到您想要使用的任何位置。
in IfcSampleInterface.ts
:
在IfcSampleInterface.ts
:
export interface IfcSampleInterface {
key: string;
value: string;
}
In SampleInterface.ts
在 SampleInterface.ts
import { IfcSampleInterface } from './IfcSampleInterface';
let sampleVar: IfcSampleInterface;
回答by Artem Koshelev
回答by CPHPython
Export only a few interfaces
只导出几个接口
Without spreading multiple exports, you can group them in one single export {}
block (in this case, no file default
type should be declared):
无需分散多个导出,您可以将它们组合在一个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 example
导入示例
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)
};
回答by CPHPython
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