繁体   English   中英

打字稿遍历键入的对象键

[英]typescript iterate over typed object keys

我目前正在研究一种快速方法来遍历javascript对象,并发现jsperf基准测试http://jsperf.com/object-keys-iteration/46可以显着提高性能(如果您使用带有字符串的数组作为键和内置的forEach函数。

通常,我以以下方式将对象声明为接口:

interface FooInterface { [key:string]:AnotherInterface; }
var foo:FooInterface = {};

但是,如果我尝试将接口添加到数组打字稿,则会引发错误:

var foo:FooInterface = [];
foo['key'] = anotherInterfaceImplementation;

Cannot convert 'any[]' to 'FooInterface'

是否有机会更新界面并提高性能?

谢谢!

您可以使用类型断言:

interface FooInterface { [key:string]:AnotherInterface; }

var foo:FooInterface = <any>[]; // ASSERT to tell the compiler that you know better
foo['key'] = anotherInterfaceImplementation;

暂无
暂无

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

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