首页 > 解决方案 > 我可以在打字稿中定义/链接类型到一个类吗?

问题描述

在打字稿中,类中是否可以有“静态类型字段”?我知道以下内容无效,但只是为了让您了解我要完成的工作:

class Collection<Item> {
  items: [Item];
  constructor() { this.items = [] }
  type ItemType = Item; // invalid
}
function for_each<Container>(
  container: Container,
  f: (val:Container.ItemType) => any // invalid
)
  { /* ... */ }
var strings = new Collection<string>();
var int_processor = function (val: number) {}
for_each(strings, int_processor); // I'd like an error here

我是打字稿的新手,我找不到是否存在做这种事情的语法(有点像 C++ 中的类中的 typedefs)。希望它允许在最后一行出现错误,以便我可以在编译时捕获我无法运行int_processorstrings.

有可能吗?

标签: typescript

解决方案


您可以添加静态属性。这是您改编的示例:

class Collection<Item> {
  items: [Item];
  static ItemType = {}; // your new ItemType here
  constructor() { this.items = [] }
}
function for_each<Container>(
  container: Container,
  f: (val:Container.ItemType) => any // invalid
)
  { /* ... */ }
var strings = new Collection<string>();
var int_processor = function (val: number) {}
for_each(strings, int_processor); // I'd like an error here

推荐阅读