Hi all, I was reading the docs for previous typescript release and saw this part: https://devblogs.microsoft.com/typescript/announcing-typescript-4-7/#optional-variance-annotations-for-type-parameters, however even after reading through the examples, I still didn't understand what it did so I googled it, but I can't find a single result about it, would anyone be able to help explain it?
#Better examples for Optional Variance Annotations for Type Parameters
11 messages · Page 1 of 1 (latest)
in allows subtypes to be passed in, out allows casting the result to a supertype
or in other words:
- for
Foo<out T>,Foo<T> extends Foo<U>whenT extends U - for
Foo<in T>,Foo<U> extends Foo<T>whenT extends U
i think this explanantion is wrong
type Extends<T extends U, U> = T;
type Foo<in T> = {};
type Bar<out T> = {};
type T1 = Extends<Foo<"foo">, Foo<string>>;
// ^^^^^^^^^^
// Type 'Foo<"foo">' does not satisfy the constraint 'Foo<string>'.
// Type 'string' is not assignable to type '"foo"'.
type T2 = Extends<Foo<string>, Foo<"foo">>;
type T3 = Extends<Bar<"foo">, Bar<string>>;
type T4 = Extends<Bar<string>, Bar<"foo">>;
// ^^^^^^^^^^^
// Type 'Bar<string>' does not satisfy the constraint 'Bar<"foo">'.
// Type 'string' is not assignable to type '"foo"'.
type Extends<T extends U, U> = T;
type Foo<T> = (arg: T) => void;
type Bar<T> = { value: T; };
type T1 = Extends<Foo<"foo">, Foo<string>>;
// ^^^^^^^^^^
// Type 'Foo<"foo">' does not satisfy the constraint 'Foo<string>'.
// Type 'string' is not assignable to type '"foo"'.
type T2 = Extends<Foo<string>, Foo<"foo">>;
type T3 = Extends<Bar<"foo">, Bar<string>>;
type T4 = Extends<Bar<string>, Bar<"foo">>;
// ^^^^^^^^^^^
// Type 'Bar<string>' does not satisfy the constraint 'Bar<"foo">'.
// Type 'string' is not assignable to type '"foo"'.
here Foo and Bar are real types for comparison
a function that accepts all strings naturally also can accept "foo"
and conversely, a value that is "foo" is also a string
thanks, this makes sense
!close