Since the variable b
can still be assigned to variable a
.
Let's look at the following example:
interface A {
a: number;
b: string;
};
interface B {
a: number;
b: string;
xxx: string;
}
declare var a: A[]
declare var b: B[]
a = b // ok
b = a // error
b
has all the properties of a
, making it safe to assign b
to a
.
However, it is not safe to assign a
to b
.
interface A {
a: number;
b: string;
};
interface B {
a: number;
b: string;
xxx: string;
}
let a:B[] = [{a:1, b:"a"}, {a:2, b:"b"}]; // error
This is because they are covariant.
If you are interested in contravariance, check out this example:
interface A {
a: number;
b: string;
};
interface B {
a: number;
b: string;
xxx: string;
}
class C<T>{
method = (a: T) => { }
}
let a: C<A> = new C()
let b: C<B> = new C()
// vice versa
a = b // error
b = a // ok