KnockoutObservableArray with typed elements in TypeScript

橙三吉。 提交于 2019-12-24 03:39:12

问题


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.

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[].

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.

Thanks in advance!


回答1:


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']);

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

var observableString: any;


来源:https://stackoverflow.com/questions/13914512/knockoutobservablearray-with-typed-elements-in-typescript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!