1
type Foo = {
    fn1(field: string | undefined): void
}

class Test implements Foo {
    fn1(field: string): void {
        console.log(field.toLowerCase())
    }
}

const x: Foo = new Test()
void x.fn1(undefined) // Compiles but crashes at runtime

Expected Behavior: I expected TypeScript to give a compile-time error, such as: "Class 'Test' incorrectly implements interface 'Foo'" since the method's signature does not match the interface's.

In particular, the fn1 method in the class Test accepts only string, but the interface Foo allows string | undefined. This mismatch leads to a runtime crash when undefined is passed to fn1.

Problem: It compiles successfully without any error, but crashes at runtime. Why does TypeScript not flag this as an error at compile-time, and how can I catch such issues?

3
  • 1
    github.com/Microsoft/TypeScript/wiki/FAQ#why-method-bivariance Commented Sep 25, 2024 at 13:10
  • Avoid method syntax if you care about contravariance of parameters; see this playground link and the questions/answers linked above. Commented Sep 25, 2024 at 13:17
  • Using function syntax instead of method syntax solved the issue. Thank you. Commented Sep 26, 2024 at 7:41

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.