Home > Net >  Typescript: Cannot find name argument in anonymous function
Typescript: Cannot find name argument in anonymous function

Time:07-15

This code snippet gives TS error: Cannot find name c.

I want to call the anonymous function b but cannot access the argument c of the anonymous function.

function fn(a: number, b: (c: number) => void) {
  b(c);
}

CodePudding user response:

You've misunderstood the params passed. The section (c: number) => void is a type, it does not mean c is a individual parameter. You can rewrite this as.

function fn(a, b) {
  b(c);
}
const c = 1234;
function test(cParam) {
  console.log(cParam);
}
fn(1, test.bind(c));

So here, b is the function test which takes one input parameter. We can use .bind(c) to let javascript know that when the b variable inside function fn executes, we should take the first paramter as c.

CodePudding user response:

Well, when you call fn, you would not pass a function with its argument. You would call it with a reference to the other function. For example:

fn(21, myOtherFunction)

Therefore, something like this works:

const fn = (a: number, b: (c: number) => void) => {
  b(a);
}

Just pass what you thought of as c as your first argument instead.

  • Related