简体   繁体   中英

Passing typed array as any[]?

Why can't I pass a typed array into a function/constructor which takes an any[] ?

typedArray = new MyType[ ... ];
items = new ko.observableArray(typedArray);

Gives me the error:

Supplied parameters do not match any signature of call target

ko.observableArray is defined as:

interface KnockoutStatic 
{
    observableArray: KnockoutObservableArrayStatic;
}

interface KnockoutObservableArrayStatic
{
    new(value: any[]): KnockoutObservableArray;
}

declare var ko: KnockoutStatic;

How do I pass my MyType[] as an any[] ? Is this a problem with covariance?

typedArray = new MyType[ ... ];

This isn't how you make a new array in JavaScript or TypeScript (in 0.9.0 this will correctly be a syntax error in the empty array case). You should just be able to write:

typedArray = [ ... ];

and have the compiler correctly infer the type as MyType[] . If needed, you can add a type annotation:

typedArray = <MyType[]>[ ... ];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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