Reputation: 95
In the following code, the type parameter T
appears in a contravariant position in the Setter
type. Why does typescript allow the assignment in a way that seems to break variance rules?
type Setter1<T> = {
set(val: T): void
}
function f1(x: Setter1<'a'>): void {
const y: Setter1<string> = x // no compile error. why?
}
On the other hand, the below code does have a compile error (which is what I would expect).
type Setter2<T> = {
set: (val: T) => void
}
function f2(x: Setter2<'a'>): void {
const y: Setter2<string> = x // compile error. good!
}
Upvotes: 1
Views: 54