TypeScript: Convert interface to class -
i have next code:
interface x { type : string; val : number; } class x1 implements x { type : string; val : number; } var p1 : x[] = [{type:'a', val:8}]; (var n in p1) { var p2 : x1 = p1[n]; } var p3 : x1 = p1[0];
both p2 , p3 declared having type x1 , initialized value of type x.
the compiler happily accepts declaration of p2, complains p3 saying "cannot convert 'x' 'x1'".
why difference?
everything implements x
should convertible x
, not convertible x1
.
here more detail. code below shows simple example. essentially, if have of type x
(interface) implemented either x1
(class) or x2
(class).
while can downgrade type (from implementation downwards interface) can't upgrade type (from interface specific implementation) because can't guarantee have compatible.
another way of looking @ can create less specific is, can't create more specific is.
interface x { type : string; val : number; } class x1 implements x { type : string; val : number; } class x2 implements x { type: string; val: number; mymethod() { } } var x1 = new x1(); var x2 = new x2(); var examplea: x = x1; // happy var exampleb: x = x2; // happy var examplec: x1 = examplea; // not happy...
the upshot of of need cast it:
var examplec: x1 = <x1>examplea; // happy...
but cautious, because this, wouldn't work:
var examplec: x2 = <x2>examplea; // seems happy... examplec.mymethod(); // oh dear!
update
in respect of piece of code...
for (var n in p1) { var p2 : x1 = p1[n]; }
in javascript isn't equivalent foreach
loop. used iterating on properties in object , when utilize on array show explicitly set indexes (not items). iterate on array, should using:
for (var = 0; < p1.length; i++) { var p2 : x1 = p1[i]; // same warning before }
so how come typescript allows p1[n]
allocated x1
variable? interesting question , reply lies here...
if hover on p1[n]
you'll see type of x[]
- type of p1
, not type of p1[n]
. if check example, you'll find p1[n]
of type any
:
var illustration = p1['test']; // used 'test' because n string.
because of type any
compiler allows tell treat x1
. converting any
x1
not x
x1
might have thought.
typescript
No comments:
Post a Comment