1

In JavaScript, I can overwrite a function:

function testf() {
    console.log('old function')
}
testf = function() {
    console.log("new function");
}

How can I do this in TypeScript? I'm writing a WebP polyfill and would like to overwrite the global createImageBitmap function, but tsc complains:

Cannot assign to 'createImageBitmap' because it is not a variable.

6
  • @musefan the first result is the current question Commented Jun 25, 2018 at 7:39
  • @bugs: I have no idea how I managed to copy the wrong link... I meant this one Commented Jun 25, 2018 at 7:41
  • you have to tell your compiler which global variables you are using. I believe there is preset to use browser globals and otherwise write your own d.ts -typing files and declare your globals that tslint can understand them. otherwise typescript is just normal javascript so your code will work even though your editor displays this error. Commented Jun 25, 2018 at 7:55
  • @musefan I'm sorry, I didn't found this question with Google before when I searched for my problem. Should I delete my question? Commented Jun 25, 2018 at 7:56
  • Don't delete it. At the worst, this one can just be closed as a duplicate Commented Jun 25, 2018 at 7:57

1 Answer 1

0

Doing someName = whatever requires that someName is defined within the current scope as a variable.

You can, however, assign to window (same as assigning the variable of any other object), which should produce the same effect:

window.createImageBitmap = customImageBitmap

Just make sure customImageBitmap has the same signature (argument types and return types) as window.createImageBitmap in order for this to pass the type checker.

Sign up to request clarification or add additional context in comments.

2 Comments

The solution is to assign to window (together with the declare function ...). I tried it without window, therefore it didn't worked.
The declare function ... is not needed. See here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.