2

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!

thomaux
  • 19,133
  • 10
  • 76
  • 103

1 Answers1

4

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;
Fenton
  • 241,084
  • 71
  • 387
  • 401
  • 2
    Citations for "Generics will be included in the final language"... discussion: https://typescript.codeplex.com/discussions/397702 language spec: http://www.typescriptlang.org/Content/TypeScript%20Language%20Specification.pdf (page 18) – Fenton Dec 17 '12 at 16:58
  • Damn, that's too bad :) Thanks for the answer and link. With the type definition file for Knockout you can specify certain properties as typed observables i.e. KnockoutObservableString, KnockoutObservableBool etc. There's also a KnockoutObservableArray but alas I don't think it'll be possible to have it define the type of the elements it'll contain. I'll accept your answer in a few days, maybe other opinions will be voiced in the mean time. – thomaux Dec 17 '12 at 17:51