A
A
Alexandroppolus2021-09-17 19:06:34
typescript
Alexandroppolus, 2021-09-17 19:06:34

Function parameter typechecking bug?

The code:

type AB = {
    a: number
    b: string
}

type A = {
    a: number
}

interface Int1 {
    f(p: A): void
    // f: (p: A) => void
}

class Class1 implements Int1 {
    f(p: AB): void { console.log(p) }
    // f = (p: AB) => { console.log(p) }
}

var o: Int1 = new Class1();

o.f({a: 1})


By the law of contravariance, Class1 does not implement the Int1 interface , because the class method f cannot take a parameter of type A .
However, typechecking is silent .

If we change the definition of f in the interface (comment-uncomment), then the error is highlighted, regardless of how we write the function in the class.

Maybe I don't understand something in this form? f(p: A): void But if here instead of A we substitute, for example, a number, then everything is fine, there is an error.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Stanislav Makarov, 2021-09-17
@Alexandroppolus

Great question.
Strict function types :

The stricter checking applies to all function types, except those originating in method or constructor declarations. Methods are excluded specifically to ensure generic classes and interfaces (such as Array) continue to mostly relate covariantly.

When replacing methods with ordinary functions, an error immediately appears:
type AFnc = (p: A) => void

function foo(p: A): void { }
function bar(p: AB): void { }

const f: AFnc = foo;
const b: AFnc = bar; // не компилируется с сообщением о том, что AB требует ещё и свойство b

W
WbICHA, 2021-09-17
@WblCHA

Because AB is a special case of A.
Roughly speaking, the typescript compares not the names of interfaces, but their properties and their types. That is, you can pass in any type that is a special case of the type you want.
If you change the property type in AB аto string, then the error will immediately appear.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question