简体   繁体   English

TypeScript:组织相关的类和接口

[英]TypeScript: Organizing related classes & interfaces

I'm porting a JavaScript project to TypeScript and I'm unsure how to organize related entities (types/interfaces/classes). 我正在将JavaScript项目移植到TypeScript,但不确定如何组织相关实体(类型/接口/类)。

Below are the different approaches I'm considering. 以下是我正在考虑的不同方法。

Prefix all interfaces with class name 给所有接口加上类名前缀

interface IFooOptions {}

class Foo {
  constructor(options: IFooOptions) {}
}

// usage
var foo = new Foo({});

Create a module: 创建一个模块:

module Foo {
  export interface IOptions {
    // ...
  }

  export class Foo {
    constructor(options: IOptions) {}
  }
}

// usage
var foo = new Foo.Foo({});

Create a module with factory function: 创建具有工厂功能的模块:

module Foo {
  export interface IOptions {
    // ...
  }

  export class Foo {
    constructor(options: IOptions) {}
  }

  export function create(options: IOptions): Foo {
    return new Foo(options);
  }
}

// usage
var foo = Foo.create({});

What are the pros/cons of these methods? 这些方法的优点/缺点是什么? Is there a convention in the community? 社区中有公约吗?

For internal modules, it would look like this: 对于内部模块,它看起来像这样:

module Foo {
  export interface FooOptions {
    // ...
  }

  export class Foo {
    constructor(options: FooOptions) {}
  }
}

// usage
var foo = new Foo.Foo({
    //...
});

The use of the I prefix on interfaces is discouraged (although it does exist in the wild). 不建议在接口上使用I前缀(尽管它确实存在于野外)。

The specificity of the interface name comes from the principle that names should be more specific the deeper you go. 接口名称的特殊性来自以下原则:名称越深,名称就应该越具体。 So you start general and get more specific, a bit like this example from C# (in C#, the I prefix is recommended for interfaces, but it is a nominal type system whereas TypeScript is structural)... 因此,您可以从C#开始,开始更通用,更具体些,例如以下示例(在C#中,建议接口使用I前缀,但这是名义上的类型系统,而TypeScript是结构性的)...

System.Data.SqlClient.SqlConnection
System.Data.FooClient.FooConnection

Note that they could have used Connection , because it is nested in SqlClient - but it actually makes you work harder to understand the code if you have to see the full namespace to know what you are dealing with. 请注意,他们本可以使用Connection ,因为它嵌套在SqlClient -但是如果必须查看完整的名称空间才能知道要处理的内容,则实际上会使您更加难以理解代码。

If the interface is common between SqlClient and FooClient , this is where you see a System.Data.IConnection , which is less nested and less specific. 如果该接口在SqlClientFooClient之间是公用的,则在此处可以看到System.Data.IConnection ,该嵌套较少且特定性较低。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM