Vovan_Super
Vovan_Super

Reputation: 525

Proper anotation for Array of Objects in KnockoutJS usin TypeScript

As, DefiantelyTyped types' definiitons were updated to use TypeSctipt with Generics, what would be the proper type in the definition (as now only ObservableArray of T is must):

class Some { 
  name: KnockoutObservable<string> = ko.observable("Some name"),
  arrayOfValues: KnockoutObservableArray< (of Object??? ) > ???? ;

  constructor () {
    arrayOfValues.push( {key: "value"} );
    ...

Upvotes: 3

Views: 1699

Answers (2)

Fenton
Fenton

Reputation: 250922

You can use TypeScript's type inference for this, as otherwise you'll end up with a long line of code that repeats itself quite a bit:

var examples = ko.observableArray<Example>();
examples.push(new Example('Test'));
examples.push('Type warning'); // not an 'Example'

In this example, you pass the type argument when you create the ko.observableArray. TypeScript infers that var examples is of type KnockoutObservableArray<Example> and checks all of your calls.

To put it into context, here is the code with your example:

interface YourType {
    key: string;
}

class Some { 
    name = ko.observable<string>("Some name");
    arrayOfValues = ko.observableArray<YourType>();

    constructor () {
        this.arrayOfValues.push( {key: "value"} );
        ...

Upvotes: 4

Poul K. S&#248;rensen
Poul K. S&#248;rensen

Reputation: 17530

KnockoutObservableArray<any> 

or define a interface for your type.

Upvotes: 3

Related Questions