1

In some old QA, I found a couple of code such as

how to extend Array in typescript

Extend native JavaScript array

I am investigating how it behaves under TypeScript.

interface Array<T> {
  "foo": Function;
  ["foo"]: Function;
}

Object.defineProperty(Array.prototype, "foo", {
  value: function <T>(this, R: T) {
    return (console.log(R));
  }
});

[].foo("test");   // test
[]["foo"]("test");  //test

Basically, the code works, The TypeScript Playground

However, for some reason, in VSCode, TypeScript produces errors

enter image description here

enter image description here

At least I tried to type the Array property.

"suppressImplicitAnyIndexErrors": true in tsconfig.json surely suppresses these errors, but I want to know how to make it work without this flag.

Any idea? Thanks.

8
  • 2
    Please share any relevant code by editing your Question - instead of a screenshot. Fewer people are likely to reproduce your issue without having your code in a copyable form. Commented Oct 25, 2021 at 14:38
  • 1
    Please provide a minimal reproducible example that clearly demonstrates the issue you are facing. Ideally someone could drop the code into a standalone IDE like The TypeScript Playground (link here!) and immediately get to work solving the problem without first needing to re-create it. Right now there are no errors in the TS Playground, so your issue isn't clear. I suspect it has to do with modules and you will need to do some global augmentation to deal with it, but without a minimal reproducible example it's just speculation. Commented Oct 25, 2021 at 14:48
  • Do you use TypeScript v4.4.4 like in the playground? Commented Oct 25, 2021 at 15:03
  • 1
    @jcalz Thanks for your playground link, and I added in my Question. I feel somewhat better it works without problem there. I don't know why my VScode environment produces the errors. Commented Oct 25, 2021 at 15:08
  • 1
    I think at this point, assuming you want to figure this out, your job is now to reproduce the issue yourself in a different environment, such as the TS Playground. Copy more of your code into the other IDE and see what happens (hint: do you have any code with export in it?) and work on it until you get a minimal reproducible example. Good luck! Commented Oct 25, 2021 at 15:12

1 Answer 1

0

Thanks a lot for your inspirations especially for @jcalz.

Here's the thing...

enter image description here

enter image description here

interface Array<T> {
  "foo": Function;
  ["foo"]: Function;
}

must be the top level of the code of TypeScript, that I really did not know.

Thank you guys anyway!!

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

Comments

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.