typescript - 我可以在打字稿中定义/链接类型到一个类吗?
问题描述
在打字稿中,类中是否可以有“静态类型字段”?我知道以下内容无效,但只是为了让您了解我要完成的工作:
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_processor
的strings
.
有可能吗?
解决方案
您可以添加静态属性。这是您改编的示例:
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
推荐阅读
- vb.net - 我计算收据的 Visual Basic 程序(使用子例程和验证函数)不工作
- javascript - 在运行时在 Gatsby 中重新运行查询
- x86-16 - 段和偏移使用
- flutter - D/FlutterActivityAndFragmentDelegate(29168):没有提供首选的 FlutterEngine。为这个 FlutterFragment.Flutter 创建一个新的 FlutterEngine:
- asp.net-mvc - MVC does not render view if querystring is used
- sql-server - 来自 Microsoft SQL Server 的整理格式不佳的数据
- node.js - SequelizeDatabaseError:关系notice_opened_tbl的权限被拒绝
- python - 数组中的 lambda 找不到变量值
- python - 将 numpy 数组中的特定值转换为 NAN
- html - Sass 插值容器高度