Why can't I cast from any[] to MyType[] in TypeScript?

2.6k views Asked by At

TypeScript has an any type that any and every arbitrary type can be cast TO OR FROM. I can cast from a variable of type any to a variable of type MyArbitraryType like in

var myThing: MyArbitraryType;
var anyThing: any;
...
myThing = anyThing;//implicit cast from 'any' to 'MyArbitraryType'
//or
myThing = <MyArbitraryType>anyThing;//explicit cast from 'any' to 'MyArbitraryType'

But I get an error when I try to cast from an any[] to a MyArbitraryType[] like in

var myThings: MyArbitraryType[];
var anyThings: any[];
...
myThings = anyThings;//implicit cast from 'any[]' to 'MyArbitraryType[]'
//or
myThings = <MyArbitraryType[]>anyThings;//explicit cast from 'any[]' to 'MyArbitraryType[]'

However I CAN do it if I use any as a middle-man like in

myThings = <MyArbitraryType[]><any>anyThings;

Which I could just use as is, but feels kinda sloppy. Is there a reason that any is castable to and from any type but any[] isn't castable to and from any array? Is this just an oversight in TypeScript so far? Or is there some other syntax I'm unaware of?

1

There are 1 answers

0
Steve Niles On

False alarm. It was Resharper, not the actual Typescript compiler, that was generating the error.