-1

I have a error with VSCode. It show me an error when I use a new method for "string":

enter image description here

When I run with npx ts-node, there is not error. How fix VsCode?

I look for VSCode not to show those errors.

Here the code:

//types.d.ts
interface String {
    test: () => string
}
//tscongig.json
{
    "compilerOptions": {
        "target": "ESNext",
        "moduleResolution": "NodeNext",
        "baseUrl": ".",
        "paths": {
            "@tools/*": [
                "tools/*"
            ],
            "@core/*": [
                "core/*"
            ]
        }
    },
    "files": [
        "types.d.ts"
    ]
}
//index.ts
String.prototype.test = () => 'hola!'

console.log('prueba'.test())

And a settings file for VSCode:

//settings.json
{
    "typescript.tsdk": "node_modules\\typescript\\lib"
}

I am executing with npx ts-node .

1 Answers1

0

First, extending the String prototype is bad practice and you should try to avoid doing that at all costs.

The error is genuine and correct. You can execute the program because it is valid JavaScript code and ts-node does transpilation, but you will not be able to compile your program to JS.

Try compiling with your code with tsc index.ts and you will get the same errors, which you will need to fix:

index.ts:1:18 - error TS2339: Property 'test' does not exist on type 'String'.

1 String.prototype.test = () => 'hola!'
                   ~~~~

index.ts:3:22 - error TS2339: Property 'test' does not exist on type '"prueba"'.

3 console.log('prueba'.test())
Alex Kolarski
  • 3,255
  • 1
  • 25
  • 35