An extension with a generic name is no longer assigned to parents

I recently upgraded to typescript 2.4, and I got a few bugs complaining that my types were no longer assigned.

Here is the scenario where I encounter an error:

interface Parent {
    prop: any
}

interface Child extends Parent {
    childProp: any
}

type Foo<T> = <P extends Parent>(parent: P) => T

function createFooFunction<T>(arg: T): Foo<T> {
    // Error here!
    return (child: Child): T => {
        return arg;
    }
}

In typescript 2.3 this is acceptable, but typescript 2.4 produces this error

Type '(child: Child) => T' is not assignable to type 'Foo<T>'.
Types of parameters 'child' and 'parent' are incompatible.
    Type 'P' is not assignable to type 'Child'.
    Type 'Parent' is not assignable to type 'Child'.
        Property 'childProp' is missing in type 'Parent'.

Regarding the last line of the error, I noticed that if I make the child properties optional, then typescript will be satisfied, that is, if I make this change

interface Child extends Parent {
    childProp?: any
}

Although this is not an ideal solution, as in my case childProp is required.

I also noticed that changing the type of the Foo argument directly in Parent will also satisfy typescript, i.e. make this change

type Foo<T> = (parent: Parent) => T

, , Foo . .dd.dd , .

, , , . Foo , -, Parent, Child - , typescript , ?

: , --noStrictGenericChecks ( ). , , , , , .

, , Child Parent, typescript , Child , OOP - ,

+4
2

, , , Child , , , Parent, Child.

, createFooFunction<T> a get Foo<T>. Foo<T> Child2, Parent Foo<T>, . , , Child , Child2.

. , Child Parent. , Child , Parent. . , , , , . , . # , in out.

#, , IEnumerable<Child> ( IEnumerable<out T>), IEnumerable<Parent>, - Child, Parent , Child Parent. IEnumerable<Child> IEnumerable<Parent>, ! Child.

, - IComparer<Parent> ( IComparer<in T>), Parent - Child Parent, Child. IComparer<Parent> IComparer<Child>, - -, Child, Child! .

in out () () . () ().

, , <P extends Parent> ( ), , Parent , . , : <P extends Parent>(parent: P) => P, P . Parent Parent, Parent, - . , , , .
+4

Source: https://habr.com/ru/post/1680764/


All Articles