Covariance / Contravariance Annotations
(It's a question as well as a suggestion)
Update: a proposal #10717
I've supposed that for structural type system as TypeScript is, type variance isn't applicable since type-compatibility is checked by use.
But when I had read @RyanCavanaugh 's TypeScript 1.4 sneak peek (specifically 'Stricter Generics' section) I realized that there's some lack in this direction by design or implementation.
I wondered this code is compiled:
function push<T>(arr: T[], a: T) { arr.push(a); }
var ns = [1];
push<{}>(ns, "a"); // ok, we added string to number[];
More clear code:
interface A { a: number; }
interface B extends A { b: number; }
interface C extends B { c: number; }
var a: A, b: B, c: C;
var as: A[], bs: B[];
as.push(a); // ok
as.push(b); // ok, A is contravariant here (any >=A can be pushed)
bs.push(a); // error, B is contravariant here, so since A<B, A cannot be pushed -- fair
bs.push(b); // ok
bs.push(c); // ok, C>=B
as = bs; // ok, covariance used?
as.push(a); // ok, but actually we pushed A to B[]
How could B[] be assignable to A[] if at least on member push is not compatible. For B[].push it expects parameters of type B, but A[].push expects A and it's valid to call it with A.
To illustrate:
var fa: (a: A) => void;
var fb: (b: B) => void;
fa(a); fa(b);
fb(a); // error, as expected
fa = fb; // no error
fa(a); // it's fb(a)
Do I understand it correctly that is by design? I don't think it can be called type-safe.
Actually, such restriction that could make B[] to be unassignable to A[] isn't desirable.
To solve it I suggest to introduce variance on some level (variable/parameter, type?).
Syntax
var as: A[]; // no variance
var bs: out B[]; // covariant, for "read"
<out A[]>bs; // ok, covariance used
<A[]>bs; // same is before, out should be inferred
(<A[]>bs)[0]; // means, allow to get covariant type
(<A[]>bs).push(a); // means, disallow to pass covariant type
<in A[]>bs; // fails
function push<T>(data: in T[], val: out T): void {
data.push(val);
}
push(animals, dog); // allowed, T is Animal
push(dogs, animal); // disallow, T can't be inferred
// In opposite
function find<T>(data: out T[], val: out T): bool { ... } // allow only get from data
find(animals, dog); // allowed
find(cats, dog); // allowed T can be inferred as Mammal
I'm not sure where variance should be applied - to variable or type? Looks like it closer to variable it self, so the syntax could be like:
var in a: number[];
function<T>(in a: T[], out b: T): { ... }
Questions to clarification
- inference variance from usage (especially for functions)
- is it applicable for types (like C# uses for interfaces/delegates)
- how to describe variance on member-level (does it need?)
- can variable be
in out(fixed type)? - can variable be neither
innorout(open for upcast/downcast)?
So this topic is a discussion point.
With the recent addition of --strictFunctionTypes co- and contra-variance are now supported on function types without function types. This was a major step up and we had to fix dozens of actual issues in our code (which is awesome!).
Are there any plans to also support co- and contra-variance for other types? (as reported in this issue)? Or nothing on the roadmap?
@nicojs the original proposal seemed to suggest adding co/contra variant annotations as a means of opting out of unsoundness on a per type basis. With --strictFunctionalTypes, that variance of a type will now be inferred correctly for other types... my covariant "interface Stream<T> { next(): T; }" behaves covariant with respect to T, and my contravariant "interface Bin<T> { put(item: T); }" behaves contravariant with respect to T.
Could you clarify, are you asking if there are any remaining soundness holes, or asking for an explicit way to declare variance (in addition to the inferred behavior)?
The proposal initially discussed here and later outlined primarily in #10717 is mostly concerned of use-site covariance annotations. The motivation use cases are still not addressed even with recent enstricten rules.
The simplest example is an array type which can be used both co- and contravariantly. With the proposal an array of type Array<out T> can only be used where type T in covariant positions (getters, methods like pop). Similarly Array<in T> can be used where type T in contravariant positions (setters, methods like push). Note, in general, Array<out T> is not the same as ReadonlyArray<T>.
@Igorbek Could you elaborate on how Array<out T> would be different from Readonly<Array<T>> (not ReadonlyArray<T> - I'm not including methods here) or Array<in T> from a theoretical Writeonly<Array<T>> (assuming some Writeonly analogue to the built-in type Readonly<T> = {+readonly [P in keyof T]: T[P]})?
@isiahmeadows consider Array's methods like pop, reverse, shift, sort, and many others. Although they are modifying array and are excluded from ReadonlyArray<T>, the type T there is in covariant position and therefore is part of Array<out T>.
@Igorbek Re-read my comment. You missed my nuance between Readonly< Array< T > > and ReadonlyArray< T > (spaces here added for emphasis).
ah, sorry @isiahmeadows I thought you were asking in the context of my previous note about their differences.
In fact, Readonly<Array<T>> is even less covariant in respect to T than ReadonlyArray<T>.
Assuming it is defined as type Readonly<T> = { readonly [P in keyof T]: T[P]; }, it only transforms own fields (not even methods) to become read-only.
Actually, TS does not currently make Readonly<T[]> be actually read-only:
function test<T>(a: Readonly<T[]>, v: T) {
a[0] = v; // no error
}
In general, generic type variance has nothing to do with read/write-ability. A simple test would be:
interface X<T> {
value: T; // read-write field with T in covariant position for reads and in contravariant position for writes
set: (value: T) => void; // read-write field with T in contravariant position
}
type Readonly<X<T>> = { // effectively equivalent to this
readonly value: T; // this is now covariant in respect to T
readonly set: (value: T) => void; // read field with T in contravariant position
}
type X<out T> = {
readonly value T; // same as Readonly
writeonly set: (value: T) => void; // see the difference
}
type X<in T> = {
writeonly value T;
readonly set: (value: T) => void;
}
And a final thing, even if in many respects having a readonly version is mostly what you want, a simple Readonly<T> cannot deal with multiple type arguments. Like imaging Processor<TIn, TOut> is contravariant in respect to TIn and covariant in respect to TOut, and therefore cannot be expressed with Readonly/Writeonly as it have mixed type arguments' variance.
Okay, I'd find a[i] = 0 succeeding when a: Readonly<number[]> to be a bug.
Okay, I'd find
a[i] = 0succeeding whena: Readonly<number[]>to be a bug.
being fixed in #29435
In the case of arrays, why not prevent aliasing assignments that aren't invariant without an explicit cast?
class Animal {}
class Dog extends Animal { bark() { } }
class Cat extends Animal { purr() { } }
const cats: Array<Cat> = [];
const goodAnimals: Array<Animal> = [new Cat, new Cat];
const badAnimals: Array<Animal> = cats; // why not make this an error?
goodAnimals.push(new Dog); // okay
badAnimals.push(new Dog); // hard to prevent, how do you tell goodAnimals from badAnimals?
cats.forEach(cat => cat.purr()); // oops!
Given TypeScript's support for generics, when are covariant arrays actually useful?
I am very excited to see that this will exist in future versions of TypeScript.
For the time being, if you're looking for a hacky way to ensure contravariance, you can add something like this to a class:
export class C<T> {
protected __forceTToBeContravariant?: (t: T) => void;
Note that you can't make this private if you want the constraint to work across TS projects due to https://github.com/microsoft/TypeScript/issues/38953 ; you might think it works in your same-project tests but not once it is encoded in .d.ts!