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

sno*_*ort 50 typescript typescript1.8

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

Aja*_*jay 66

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

IfcSampleInterface.ts:

export interface IfcSampleInterface {
   key: string;
   value: string;
}
Run Code Online (Sandbox Code Playgroud)

SampleInterface.ts

import { IfcSampleInterface } from './IfcSampleInterface';
let sampleVar: IfcSampleInterface;
Run Code Online (Sandbox Code Playgroud)

  • 这是我最初尝试的语法,但是却遇到了错误。 (2认同)

Art*_*lev 34

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

  • 这怎么可能是一个可以接受的答案。你可能认为它倾向于正确的方向(而且可能确实如此),但是我们必须寻找文章列表才能找到 Artem 暗示的答案的通用链接相当于说“我是不解释共产主义了,去网上搜一下” (15认同)
  • 这是IMO的正确答案.如果您的文件只定义了一个接口,这是首选的方式,并且更加清晰. (4认同)
  • 如果您在同一文件夹中有“ module.ts”和“ module.d.ts”,编译器将跳过“ module.d.ts”文件,因此不会考虑您的声明。重命名d.ts文件或将其移动到另一个文件夹。如果您有一个*适当的模块*,那么这种方法很好,但是如果您想在模块之间共享*类型*,最好使用`..from..`。 (4认同)
  • 对于那些试图为类型存储库中尚未涵盖的代码编写自己的“.d.ts”文件的人来说,链接到DefinitelyTyped的源代码并不是一个答案。 (4认同)

CPH*_*hon 13

只导出几个接口

无需分散多个导出,您可以将它们分组为一个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,
}
Run Code Online (Sandbox Code Playgroud)

导入示例

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)
};
Run Code Online (Sandbox Code Playgroud)


小智 7

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

import type { xxx } from './xxx'
Run Code Online (Sandbox Code Playgroud)

参考:TypeScript 文档

  • 在使用 vite 的 Vue3 应用程序中,“type {”帮助我解决了一个巨大的烦人问题。谢谢 (2认同)