【问题标题】:TypeScript enforce all files in a folder export a class which extends another classTypeScript 强制文件夹中的所有文件导出一个扩展另一个类的类
【发布时间】:2018-09-05 03:39:59
【问题描述】:

如果我有一个文件夹:

jobs/
  a.ts
  b.ts
  c.ts

有没有办法使用 TypeScript 让作业文件夹中的所有文件都导出相同的界面?

我希望 a.ts、b.ts、c.ts 都导出同一个界面。

【问题讨论】:

  • 你能澄清你的意思吗?您的意思是希望这些文件中的每一个都具有实现特定接口的默认导出?
  • 不,没有办法仅通过文件位置来强制执行。每个文件必须implement一个接口或extend一个类。

标签: typescript typescript-typings tsc


【解决方案1】:

不太确定您在寻找什么,但您可以这样做:

jobs目录中:

a.ts:

 export interface MyInterface {
   color: string;
 }

b.ts:

 export interface MyInterface {
   name: string;
 }

c.ts:

  export interface MyInterface {
    age: number;
  }

然后,是其他一些文件,你可以有这个:

 import { MyInterface } from './jobs/a';

 export class SomeClass implements MyInterface {
     color: string;
 }

在不同的文件中,你可以有这个:

 import { MyInterface } from './jobs/b';

 export class SomeClass implements MyInterface {
     name: string;
 }

在另一个不同的文件中,你可以有这个:

 import { MyInterface } from './jobs/c';

 export class SomeClass implements MyInterface {
     age: number;
 }

除非有一个非常好的、防弹的理由,否则我认为这根本不是一个好主意。很容易混淆并导入/修改错误的东西,给自己造成不必要的麻烦。

从技术上讲,从 a、b 和 c 导出的所有三个接口都可以具有相同的参数(就像它们都有 name: string)...基本上是一样的...也许您正在对冲变化之后?您可以为该 FYI 扩展接口。

您能进一步解释您要完成的工作吗?

  • 编辑 *

您不能将所有这些都放在同一个文件中:

import { MyInterface } from './jobs/a';
import { MyInterface } from './jobs/b';
import { MyInterface } from './jobs/c';

 export class SomeClass implements MyInterface {
     age: number;
 }

 export class SomeOtherClass implements MyInterface {
     color: string;
 }

 export class SomeOtherOtherClass implements MyInterface {
     name: string;
 }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-09-05
    • 2010-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-15
    • 1970-01-01
    相关资源
    最近更新 更多