Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript: subtyping and covariant argument types

Common sense suggests that subtyping should be covariant with respect to return type but contravariant with respect to argument types. So, the following should be rejected, because of the strictly covariant argument type of E.f:

interface C {
   f (o: C): void
}

interface D extends C {
   g (): void // give D an extra service
}

class E implements C {
   // implement f with a version which makes stronger assumptions
   f (o: D): void {
      o.g() // rely on the extra service promised by D
   }
}

// E doesn't provide the service required, but E.f will accept
// an E argument as long as I invoke it via C.
var c: C = new E()
console.log('Try this: ' + c.f(c))

Indeed, running the program prints

Uncaught TypeError: o.g is not a function

So: (1) what's the rationale here (presumably there is one, however unsatisfying and JavaScripty); and (2) is there any practical reason why the compiler can't omit a warning in this situation?

like image 735
Roly Avatar asked Sep 19 '16 08:09

Roly


People also ask

What is type {} TypeScript?

TypeScript has another type called empty type denoted by {} , which is quite similar to the object type. The empty type {} describes an object that has no property on its own.

Does TypeScript enforce types?

Bookmark this question.

How do you check TypeScript type?

Use the typeof operator to check the type of a variable in TypeScript, e.g. if (typeof myVar === 'string') {} . The typeof operator returns a string that indicates the type of the value and can be used as a type guard in TypeScript.


1 Answers

As per krontogiannis' comment above, when comparing function types, one can be a subtype of the other either because a source parameter type is assignable to the corresponding target parameter type, or because the corresponding target parameter type is assignable to the source parameter type. In the language specification this is called function parameter bivariance.

The reason for permitting bivariant argument types, as opposed to the "naive" expectation of contravariance, is that objects are mutable. In a pure language contravariance is the only sane option, but with mutable objects whether covariance or contravariance makes sense depends on whether you're reading from or writing to the structure. Since there's no way (currently) to express this distinction in the type system, bivariance is a reasonable (albeit unsound) compromise.

like image 94
Roly Avatar answered Oct 20 '22 08:10

Roly