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)
Art*_*lev 34
使用definition(d.ts)文件和命名空间,无需以这种方式导入/导出模块.DefinitelyTyped项目有指导和大量的例子如何做.
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)
| 归档时间: |
|
| 查看次数: |
49776 次 |
| 最近记录: |