TypeScript
TypeScript copied to clipboard
Unable to assign object literal to generically typed field
I am unable to assign an object literal to an extended generic type without a cast, and when the type has optional fields not even a cast will compile. I've tested the below using 1.5.0-beta
interface Foo {
x?: string;
y?: number;
}
interface Goo {
x: string;
y: number;
}
class Bar<P, T>{
someVar:T;
otherVar:P;
}
/* this works */
class SimpleBar extends Bar<Foo,Goo>{
constructor(){
super();
this.otherVar = {
x: 'def',
y: 42
}
this.someVar = {
x: 'abc',
y: 76
}
}
}
/* this doesn't */
class TypedBar<S extends Foo, Q extends Goo> extends Bar<Q, S>{
constructor(){
super();
// requires cast to compile, even though the literal is a valid Goo
this.otherVar = <Q>{
x: 'def',
y: 42
}
// even a cast doesn't work here (compiler error)
this.someVar = <S>{
x: 'abc',
y: 56
}
}
}
Since the object literals meet the requirements of the generic interface I should be able to assign them to the field, but the compiler does not allow this.
Consider this:
interface Baz extends Foo {
additionalValue;
}
var typedBar: TypedBar<Baz, Baz>;
typedBar.someVar.otherValue; // This is valid since T is Baz, though your implementation assumes it is just a Foo
in your example, we know that T is at least a Foo, so
var t: T;
var f: Foo;
f = t; // OK nothing wrong here
t = f; // Error. t can be more than just a foo