#Better examples for Optional Variance Annotations for Type Parameters

11 messages · Page 1 of 1 (latest)

versed stream
plush cosmos
#

or in other words:

  • for Foo<out T>, Foo<T> extends Foo<U> when T extends U
  • for Foo<in T>, Foo<U> extends Foo<T> when T extends U
plush cosmos
grave otterBOT
#
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"'.
plush cosmos
#

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

versed stream
#

thanks, this makes sense

plush cosmos
#

!close