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.
@Igorbek I meant in the case of generics.
@aleksey-bykov Sorry for not fully reading your comment before posting...
I do suspect that adding support for this might allow fixing #6102 later as well. It'd be a breaking change, but after proper generic covariance and contravariance support is added, that would be more likely to be fixable.
Really need this feature. Not much point in using inheritance if fuctional-bivariance means that a base class can be passed to a method taking an inherited type.
This should not be possible.
class Animal {}
class Cat extends Animal {}
function run(cat: Cat) {}
run(new Animal());
@schotime it's possible not because of variance. It's possible because Cat and Animal are structurally compatible. If you define Cat with a private field, it wouldn't work:
class Cat extends Animal { private x; }
The actual issue with variance and base/derived classes see in comment
the example that is killing me:
interface A {
x: string;
}
interface B {
x: string;
y: string;
}
function copyB(value: B): B {
return undefined;
}
var values: A[] = [];
values.map(value => copyB(value)) // fails as expected
values.map(copyB); // <-- expected to fail, but it does not
https://github.com/Microsoft/TypeScript/issues/3067
@Igorbek Apologies. This is a better example.
class Animal {
}
class Cat extends Animal { private x; }
function run(input: (a: Animal) => void) {
input(new Animal());
}
function cat(c: Cat) {
}
run(cat);
@schotime IIUC, those still structurally match.
type input = (a: Animal) => void;
type cat = (c: Cat) => void;
The problem is that TypeScript is structural, not nominal. There's currently no way to specify any nominal types other than enums, nominal subtypes of number.
So I believe this directly depends on #202. I may be wrong, but it's an educated guess.
You need to be clearer when you say they structurally match. A callback requiring a cat cannot be happy when fed by a random animal, say, a whale. In this sense they are not a near match.
On Aug 24, 2016 7:42 PM, "Isiah Meadows" [email protected] wrote:
@schotime https://github.com/schotime IIUC, those still structurally match.
type input = (a: Animal) => void;type cat = (c: Cat) => void;
The problem is that TypeScript is structural, not nominal. There's currently no way to specify any nominal types other than enums, nominal subtypes of number.
So I believe this directly depends on #202 https://github.com/Microsoft/TypeScript/issues/202. I may be wrong, but it's an educated guess.
— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub https://github.com/Microsoft/TypeScript/issues/1394#issuecomment-242241651, or mute the thread https://github.com/notifications/unsubscribe-auth/AA5PzaRQaBU0xu8IvUPZ3-HRpDg2jZtjks5qjNbOgaJpZM4DFNK8 .
@aleksey-bykov I stand corrected. It may indeed not depend on #202, then.
Please see my proposal #10717 that addresses the issue. Also published version. I'm looking for a feedback from the TypeScript team and the community.
Since no one has mentioned either of the most compelling examples -- arrays and promises. I've added one for good measure:
var p: Promise<{}> = ...;
var p2: Promise<string>;
p2 = p;
p2.substr(s => s.substr(2)); // runtime error, no method substr on number
Normally you can't assign {} to string without a cast, but due to function argument bivarance, you can assign a Promise<{}> to Promise<string>, or assign a {}[] to string[].
I'd say that's the most compelling reason of all, given the popularity of promises.
On Tue, Sep 13, 2016, 11:57 Aaron Lahman [email protected] wrote:
Since no one has mentioned either of the most compelling examples -- arrays and promises. I've added one for good measure:
var p: Promise<{}> = ...; var p2: Promise
; p2 = p; p2.substr(s => s.substr(2)); // runtime error, no method substr on number Normally you can't assign {} to string without a cast, but due to function argument bivarance, you can assign a Promise<{}> to Promise
. — You are receiving this because you commented. Reply to this email directly, view it on GitHub https://github.com/Microsoft/TypeScript/issues/1394#issuecomment-246730458, or mute the thread https://github.com/notifications/unsubscribe-auth/AERrBHcXTVK7XcWGPn93nlMyRsQKN_1Tks5qpsffgaJpZM4DFNK8 .
@aaronla-ms note that even non-bivariant promise types can be cross-assigned at present. It's another promise issue that masks the bivariance issue.
var p: Promise<number> = ...;
var p2: Promise<string>;
p2 = p;
p2.then(s => s.substr(2)); // runtime error, no method 'substr' on number
@yortus ah yes, I should have clarified that I'm using a simplified promise definition that doesn't suffer from the bug you mentioned:
interface Promise<T> {
then<U>(cb: (value: T) => U | Promise<U>, errcb?: (err: Error) => U | Promise<U>): Promise<U>;
}
Even then, you're able to unsoundly assign Promise<{}> to Promise
FYI this came up in the suggestion backlog slog as parameter bivariance is quite problematic for Promises specifically. We'll be thinking about this more - co/contravariance annotations are the only way out of that particular pickle and it may not be as scary as we think it is.
Awesome, thanks for considering this! I know its from a couple years ago, but re your comment:
If function parameters weren't bivariant, Array
would not be a structural subtype of Array due to members like forEach.
Array<T>.forEach by itself doesn't seem like it would cause any trouble if Array was solely covariant instead of bivariant. E.g. in .NET you have ForEach<T> available as an extension method of the covariant IEnumerable<T>.
However it is true that when you arrive at index assignment you are forced to make Array itself invariant. You can work around this by having two interfaces, a covariant "iterable" interface and a contravariant "indexable collection" interface like so:
// Mark this as covariant
interface Iterable<out T> {
readonly[index: number]: T;
length: number;
}
// Mark this as contravariant
interface NumericHash<in T> {
[index: number]: T;
}
interface Array<T> implements Iterable<T>, NumericHash<T> { ... }
Now in the consumer's code:
interface Animal { eat(): void }
interface Dog implements Animal { woof(): void; }
let animals: Animal[];
let dogs: Dog[];
let llama: Animal;
let dog: Dog;
// These two are illegal (due to appropriate variance rules)
dogs[0] = llama;
animals.forEach((d: Dog) => d.woof());
// However, these two are fine
animals[0] = dog;
dogs.forEach((a: Animal) => a.eat());
@masaeedu the code
// Mark this as contravariant
interface NumericHash<in T> {
[index: number]: T;
}
would not really work since the indexer here is for both read and write. Contravariant type would require only write-only side of the index signature which is not supported at the moment.
In my proposal #10717 I'm pointing a way to leave types like Array unchanged but leverage use-site variance annotations that would make Array<in T> to be a supertype of Array<T> where any supertype of T can be safely passed (usually that means for write purposes), accordingly Array<out T> to be a super type of Array<T> where any subtype of T can be safely passed (usually for read purposes).
@Igorbek Ah, okay. That one is just nice to have though, I don't think anyone really cares about using array indexing contravariantly. You could just bake it into the invariant Array type. E.g. in .NET you have the IEnumerable covariant interface implemented by lists, but they didn't bother making a separate contravariant interface for assignment.
Your approach is probably the most pragmatic, but I would still really like contra and covariant type annotations to be owned by whoever defines the interface, rather than whoever consumes it. From my pattern of coding at least, having to constantly remember and specify the modifiers where I'm consuming the code would not help me catch bugs. YMMV.
Another completely unsafe example:
interface MyComponent<T> {
items: T[]
selectedItem: T
onChange: Handler<T>
}
type Handler<T> = (val: T) => void
function onChange(item: string) {
console.log(item.slice(2))
}
const comp: MyComponent<string | null> = {
items: ['a', 'b', 'c'],
selectedItem: null,
onChange
}
Everything compiles fine but the onChange function can actually get passed a null reference, and that will throw at runtime.
With the available tools present in the language, we are nearly to the point where having functions default to contravariant will accomplish most usage scenarios:
declare func((x: string) => void);
func(() => { }); // Valid
func((x: 'foo') => { }); // Compiler error
// Want a covariant function? Generics will let you write one
declare func2<S extends string>((x: S) => void);
func(() => { }); // Invalid
func2((x: 'foo') => { }); // Valid
// How about a function that can operate on an array of any type of Animal?
declare function sortByWeight<A extends Animal>(animals: Array<A>): void;
Edit: adjusted last examples.
Regarding the argument that co-/contravariance are hard-to-grasp concepts - I think this is irrelevant considering that interface assignment compatibility tracks co-/contravariance even without annotations, and therefore in order for a person to understand what's going on, they need to understand the co-/contravariance (though I think it's covariance vs bivariance currently) distinction anyway.
interface Setter<T> {
set(value: T);
}
let sA1: Setter<{}> = { set() {} };
const sA2: Setter<number> = sA1;
let sB1: Setter<number> = { set(value: number) {} };
const sB2: Setter<{}> = sB1; // succeeds due to parameter bivariance
interface Getter<T> {
get(): T;
}
let gA1: Getter<{}> = { get() { return {}; } };
const gA2: Getter<number> = gA1; // Type '{}' is not assignable to type 'number'.
let gB1: Getter<number> = { get() { return 1; } };
const gB2: Getter<{}> = gB1; // succeeds due to covariant returns
For a long time, I didn't understand that TypeScript tracks the generic variance, and therefore the distinction between Promise
EDIT: Or rather, I understand now that structural typing results in effects as if TypeScript tracked variance across interface boundaries.