Home > Software engineering >  is it possible to assign a function to another function in typescript
is it possible to assign a function to another function in typescript

Time:02-04

I want to set current function to null loop in typescript, this is my code looks like:

export function noop() {}

export function removeFirstMouseUp() {
  removeFirstMouseUp = noop;
}

but the compiler told me this error:

 TS2630: Cannot assign to 'removeFirstMouseUp' because it is a function.

assign a function to another function, it seems no problem. why the typescript compiler shows this error? what did I do to fix this problem?

CodePudding user response:

You can only change a function expression and not a function declaration. If you store a function expression in a variable and return it from an exported function then you can change it.

const noop = () => {}

const firstMouseUp = () => {
}

let func = firstMouseUp;

export function getFunc () {
  return func;
}

export function removeFirstMouseUp() {
  func = noop;
}

Play here

CodePudding user response:

Instead of defining removeFirstMouseUp as a function declaration, rewrite it as a function definition:

export function noop() {}

export let removeFirstMouseUp = function() {
    removeFirstMouseUp = noop;
} 

From ESLint's no-func-assign page:

JavaScript functions can be written as a FunctionDeclaration function foo() { ... } or as a FunctionExpression var foo = function() { ... };. While a JavaScript interpreter might tolerate it, overwriting/reassigning a function written as a FunctionDeclaration is often indicative of a mistake or issue.

ESLint and TypeScript are different, however, in this case the error messages are referring to the same thing.

CodePudding user response:

It would seem you are just looking for

export function noop() {}

export function removeFirstMouseUp() {
  return(noop);
}
  •  Tags:  
  • Related