【问题标题】:What is the naming convention for a Type and the Class that implements it?类型和实现它的类的命名约定是什么?
【发布时间】:2019-11-24 04:15:03
【问题描述】:

我有一个类 DropdownItem,它为下拉选项创建蓝图。

class DropdownItem {
  value: string;
  name: string;
  ....
}

还有其他选项可以将其命名为 DropdownItemInterface

interface DropdownItemInterface  { // ???
  value: string;
  name: string;
}

最佳做法是什么,或者有什么最佳做法?

【问题讨论】:

  • 你为什么需要它? DropdownItem 都指一个类和一个类型
  • 你是对的,在这种特殊情况下它是多余的,尽管如果我使用类作为类型,打字稿不会向我展示它的洞察力。
  • @George.S - 应该。操场适合我。如果我输入 const item: DropdownItem = {,然后 Ctrl+Space 将显示 valuename 选项供我选择。
  • @T.J.Crowder 我在 VSCode 中使用它。它只是一个代码编辑器功能,我可以通过它至少显示它所指的类类型。
  • @T.J.Crowder 我也让它为我工作。再次感谢您,祝您编码愉快!)

标签: javascript typescript types typescript-typings


【解决方案1】:

约定是只使用类名作为类型。与大多数(但不是所有)具有类的语言一样,类定义了实现接口。您可以定义一个单独的接口,但这不是必需的,标准做法是不这样做。

请注意,在 TypeScript 中,事物是赋值兼容的,即使它们没有通过声明的接口建立类型关系。例如:

class DropdownItem {
  value: string = "";
  name: string = "";
}

function example(item: DropdownItem): void {
    //...
}

const item1 = {value: "x", name: "foo"};

example(item1);  // No error here, even though `item1` is not
                 // declared of type DropdownItem

事实上,你作为DropdownItem 使用的内容只需要具有正确类型的valuename,即使它还有其他内容:

const item2 = {value: "y", name: "bar", other: 42};

example(item2);  // No error here, it's okay that it has an
                 // extra property

Examples on the playground.


如果您确实决定使用单独的接口,我认为没有任何一种标准的接口命名方式。我在 TypeScript 中看到的大多数接口都只是以正常方式命名,没有任何特定的指示它们是接口。在使用指标的极少数情况下,它通常是 I 前缀,例如IDropDownItem,但我怀疑我主要在人们使用其他语言或(显示我的年龄)COM 编写的代码中看到了这一点。

【讨论】:

  • 嗯,我有一种感觉,应该是这样。谢谢解释
  • 旁注:如果我不想要一个类,我有时会创建一个类型/组合:type User = { ... }; const User = { create(): User { ... }, ... };
猜你喜欢
  • 2018-04-15
  • 2012-11-25
  • 2017-12-03
  • 2010-12-29
  • 2011-07-22
  • 2013-03-13
  • 1970-01-01
  • 1970-01-01
  • 2018-10-16
相关资源
最近更新 更多