使用TypeScript中的类型化元素的KnockoutObservableArray [英] KnockoutObservableArray with typed elements in TypeScript

查看:88
本文介绍了使用TypeScript中的类型化元素的KnockoutObservableArray的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在寻求将我们的项目迁移到TypeScript.我发现了很好的定义文件集,而我目前正在为淘汰赛.

I'm currently looking to migrate our project to TypeScript. I've found this great set of definition files and I'm currently experimenting with the one for Knockout.

我知道定义文件具有observableArray KnockoutObservableArray的类型,并且我也知道您可以定义像MyType[]这样的类型化数组.

I know the definition file has a type for the observableArray KnockoutObservableArray and I also am aware you can define a typed array like MyType[].

我想知道我是否可以将两者结合起来?我想创建一个KnockoutObservableArray,其元素应为MyType类型.

I'd like to know if I can somehow combine these two? I'd like to create a KnockoutObservableArray for which the elements should be of type MyType.

提前谢谢!

推荐答案

TypeScript的路线图包括泛型,我认为这是创建所需内容所需要的.以下代码不是真实的,甚至可能不是TypeScript团队实现泛型的方式,但它提供了我认为将如何实现的方式.我还省略了如何使其可观察等的实现细节:

The road-map for TypeScript includes generics, which I think is what you need in order to create what you want. The following code isn't real and may not even be how the TypeScript team implement generics, but it gives a flavour of how I think it would be implemented. I have also left out implementation details on how to make it observable etc:

class KnockoutObservableArray <T> {
    constructor(public Items: T[]) {
    }
}

var observableString = new KnockoutObservableArray<string>(['foo', 'bar']);

但是正如我提到的那样,泛型尚未包含在TypeScript中,因此现在您必须使其具有动态性!

But as I mentioned, generics aren't yet included in TypeScript, so for now you'll have to make it dynamic!

var observableString: any;

这篇关于使用TypeScript中的类型化元素的KnockoutObservableArray的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆