Troy
Troy

Reputation: 13

No compilation error for a missing parameter

Foo is declared as an object with a member func that is a function that requires 2 parameters. The use of Foo in the footable definition specifies a function that only takes 1 parameter. Why doesn't it give a compiler error?

interface Foo {
  func: (x: number, y: number) => void;
}

const footable: { [k:string]: Foo } = {
  entry: { func: (x: number): void => {} },
}

Upvotes: 1

Views: 51

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249586

This is the expected behavior. In general typescript will not complain about a function with fewer parameters being assign to a reference that expects more parameters. The reason is that when calling the extra parameters are ignored and no runtime errors occur

let fn: (x: number, y: number) => void = () => console.log("I don't care about any arguments!")
fn(1,2)

You can force a strict number of parameters using tuples in rest parameters and an intersection with a strict length, but I would not use this unless you have a very good reason for it:

interface Foo {
    func: (...a: [number, number] & { length: 2 }) => void;
}

const footable: { [k: string]: Foo } = {
    entry: { func: (x: number): void => { } }, //err
    entry2: { func: (x, y): void => { } }, // ok
}

footable[""].func(1, 2);

Upvotes: 1

Related Questions