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


78

我想在基于打字稿的项目中在自己的文件中定义几个接口,从中我将实现用于生产的类以及用于测试的模拟。但是,我不知道什么是正确的语法。我已经找到了很多有关声明接口和实现接口的教程,但是它们都在同一个文件中实现了接口和派生类的简单实现,而这在现实世界中并不是很真实。导出和导入接口的正确方法是什么?

Answers:


111

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

IfcSampleInterface.ts

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

SampleInterface.ts

import { IfcSampleInterface } from './IfcSampleInterface';
let sampleVar: IfcSampleInterface;

3
这是我最初尝试的语法,但是却遇到了错误。
哼了一声

1
@snort能否详细说明您遇到的错误类型?
阿贾伊

看起来问题在于类型名称不能用作Aurelia中的键(或者我只是不知道如何正确地声明它)。错误为“找不到名称[BTAuthService]”。此代码给出错误:container.registerSingleton(BTAuthService,MockAuthService); 如果我先将接口分配给var并将其传递给registerSingleton,我不会出错。

我想我对TS / JS构造函数和类型名称有误解。

接口类型从已编译的代码中消除,因此会出错。将此标记为我未完成问题的正确答案。真正的问题是在这种特定情况下,我试图将接口的名称用作类型名称。
2016年

60

使用定义(d.ts)文件和名称空间,无需以这种方式导入/导出模块。DefinitelyTyped项目提供了指导和大量示例


5
这是IMO的正确答案。如果您的文件仅定义一个接口,则这是首选方法,并且更加干净。
orad

8
如果你有module.tsmodule.d.ts在同一个文件夹中,编译器会跳过module.d.ts文件,所以你的声明将不被考虑。重命名d.ts文件或将其移动到另一个文件夹。如果您有合适的模块,这种方法很好,但是如果您想在模块之间共享类型,最好使用import .. from ..
jpenna

4
这怎么是一个可以接受的答案。您可能会认为它朝着正确的方向倾斜(而且可能确实如此),但是指向我们必须搜寻的文章列表的通用链接才能找到Artem所暗示的答案,这等同于说:“我是不打算解释共产主义,去搜索互联网”
airtonix

我已经添加d.ts到我的react项目中,但是我仍然需要导入接口。
Hamid Mayeli

10

仅导出一些接口

在不分散多个导出的情况下,可以将它们分组在一个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)
};

3

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

interface X{
    ...
}
export default X

ts

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

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

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.