Search code examples
typescriptecmascript-6tsc

object shorthand syntax in typescript compiler


interface o {
  name: string
}
const func = (obj: o): boolean => true

// this should throw error message.(or warning message at least, but it doesn't)
func({ name })

name is undefined in the code I wrote, so func({ name }) should throw an error I think. Is this intended?
Can I fix this with eslint or tsc config?


edit: this isn't a duplicate
I'm in node and Global.name is undefined.
It seems tsc thinks name is string though.

my tsconfig.json:

{                                                                                                                                                                               
  "compilerOptions": {                                                                                                                                                          
     "experimentalDecorators": true,                                                                                                                                             
     "emitDecoratorMetadata": true,                                                                                                                                              
     "skipLibCheck" : true,                                                                                                                                                      
     "rootDir": "./src",                                                                                                                                                         
     "outDir": "./src/js"                                                                                                                                                        
   }                                                                                                                                                                             
}

Solution

  • TypeScript declares a global called name in lib.dom.d.ts because of window.name.

    name is declared with type never but that doesn't prevent it from being an issue. There is a discussion on Github on changing it's type to void in which case there would be an error in your example. A workaround is to configure ESLint with the rule no-restricted-globals.


    However, since you're compiling for Node.js, there is actually a much better solution. Because you don't need any type definitions for DOM APIs it's best to not include lib.dom.d.ts at all.

    You can do this by specifying the lib compiler option explicitly in tsconfig.json:

    {
        "compilerOptions": {
            "lib": [
                "ES5"
            ]
        }
    }
    

    Note: the exact value for lib you'll need depends on your project. See the compiler options documentation for all available values and the defaults for different targets