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

问题描述 投票:0回答:6

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

typescript typescript1.8
6个回答
211
投票

您需要从定义的文件中导出接口,然后将其导入到您想要使用的任何地方。

IfcSampleInterface.ts

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

SampleInterface.ts

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

92
投票

使用定义(

d.ts
)文件和命名空间,无需以这种方式导入/导出模块。 DefinelyTyped 项目有 指导 和大量 示例 如何做到这一点。


25
投票

仅导出少数接口

无需分散多个 exports,您可以将它们分组到一个

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)
};

7
投票

您可以在相对较新的项目中使用以下语法

`import type { xxx } from './xxx'`

https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-8.html


4
投票

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

x.ts

interface X{
    ...
}
export default X

y.ts

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

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


0
投票

接受的答案是正确的:您只需从其模块中导出接口并从其使用模块中导入它即可。

有一个有用的技巧需要知道。即使你的模块只包含类型和接口,但没有“真正的”代码,TypeScript 仍然会生成一个相当无用的 .js 文件 (如果你的模块以 .ts 扩展名命名),但如果它以 命名,则会跳过生成。 d.ts。导入端的文件路径相同:带有 .js 扩展名的模块名称。

// Module Foo.d.ts containing only types
export interface IFoo {}

// Module Client.ts
import {IFoo} from './Foo.js'
© www.soinside.com 2019 - 2024. All rights reserved.