2

Basic question: Is it possible to type-check only imports?

I do want to know

  • TS: property 'id' does not exist on type 'Stripe.customer' (for example)
  • but not on my own objects, like property 'prop1' does not exist on type '{}'

Background

  • I'm working on a Javascript project, and I'd like to use Typescript for added intellisense with imported libraries, while otherwise writing in JS, so I've changed my .js file to .ts during development. († see bottom)

  • In the Javascript project, lots of objects are initialized as let x = {} and then properties are later added as x.prop1 = value1.

  • TSLint then warns me, property 'prop1' does not exist on type 'x'.

I would like to get this warning only on imports.

  • For instance, if I import * as stripe from 'stripe', then it's helpful to get the warning property 'id' doest not exist on type 'customer'.

  • Following this thread, property does not exists on type '{}' , I can achieve this manually on a per-object basis by converting x.prop1 to x['prop1'].

  • I've also experimented with inline comments to disable various TSLint rules, but the warnings are coming from the Typescript language features in VSCode, not TSLint.

However, to restate the question more precisely: Is there directive or config option that would allow me to add properties to objects defined in my own code without warning, while still warning/type-checking imported libraries?

† If there's a alternative, less janky way to get intellisense on imported libraries in Javascript, I'm all ears!

ultraGentle
  • 5,084
  • 1
  • 19
  • 45

1 Answers1

0

Ultimately, I was able to achieve this by

  1. keeping my file extension .js instead of .ts (which I was only using becuse I thought it was necessary to enable type checking)

  2. adding a tsconfig.json file to my project, with the following settings to enable type checking JS:

{
  "compilerOptions": {
    "module": "commonjs",
    "allowJs": true,
    "checkJs": true,
    "strict": false,
    "noImplicitReturns": true,
    "noImplicitAny": false,
    "noUnusedLocals": false,
    "strictPropertyInitialization": false,
    "outDir": "lib",
  },
  "compileOnSave": false,
}

The result was that I could write x.myProp without warning, but importedLibrary.propThatDoesNotExist would throw a Typescript error.

And because compileOnSave is false, the compiler didn't actually take any actions, it just issues warnings -- effectively allowing some added TS features in a JS file, which is quite useful.

I believe this works because it's a Javascript file, and thus the TS compiler expects JS-style coding, but I'm not 100% sure.

Finally, a useful reference for the compiler options above: https://www.typescriptlang.org/docs/handbook/compiler-options.html

ultraGentle
  • 5,084
  • 1
  • 19
  • 45