TypeScript 强制文件夹中的所有文件导出 class 扩展另一个 class

TypeScript enforce all files in a folder export a class which extends another class

如果我有一个文件夹:

jobs/
  a.ts
  b.ts
  c.ts

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

我希望 a.ts、b.ts、c.ts 都导出相同的接口。

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

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

除非有一个非常好的、无懈可击的理由,否则我认为这根本不是一个好主意。真的很容易混淆,import/modify 做错事,给自己造成不必要的麻烦。

从技术上讲,从 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;
 }