microsoft / TypeScript

TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
https://www.typescriptlang.org
Apache License 2.0
101.2k stars 12.51k forks source link

Ambient reference silently included in all files #58911

Closed cuttin-n-pastin closed 5 months ago

cuttin-n-pastin commented 5 months ago

🔎 Search Terms

ambient reference

🕗 Version & Regression Information

⏯ Playground Link

https://github.com/cuttin-n-pastin/tsjsdocref-repro

💻 Code

[package.json]

{
  "name": "repro",
  "version": "1.0.0",
  "description": "",
  "scripts": {
    "tsc": "tsc --noEmit"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "typescript": "^5.4.5"
  }
}

[tsconfig.json]

{
  "include": ["*.js"],
  "compilerOptions": {
    "types": [],
    "paths": {
      "*": ["./*.js"]
    },
    "moduleDetection": "force",
    "target": "es2021",
    "module": "commonjs",
    "lib": ["ES2022"],
    "allowJs": true,
    "outDir": "./dist",
    "strict": true,
    "noImplicitAny": true,
    "strictNullChecks": true                       ,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "resolveJsonModule": true
  }
}

[types/index.d.ts]

declare type MyType = 'foo' | 'bar' | 'baz';

[f1.js]

/// <reference types="./types" />

/** @type {MyType} */
const f = 'foo';

[f2.js]

// @ts-check

/** @type {MyType} */
const f = 'oof';

🙁 Actual behavior

f2.js:4:7 - error TS2322: Type '"oof"' is not assignable to type 'MyType'.

4 const f = 'oof';
        ~

Found 1 error in f2.js:4

🙂 Expected behavior

f2.js:3:12 - error TS2304: Cannot find name 'MyType'.

3 /** @type {MyType} */
             ~~~~~~

Found 1 error in f2.js:3

Additional information about the issue

No response

jakebailey commented 5 months ago

Reference directives are just another way to include a file in a project; they do not have the power to make ambient types only visible in a single file.

cuttin-n-pastin commented 5 months ago

Thank you for your answer. The existing documentation does not make that clear.

What can I use to reference specific ambient types per .js file (that uses JSDoc syntax)?

RyanCavanaugh commented 5 months ago

There isn't a way to do that; you'd need separate tsconfigs

typescript-bot commented 5 months ago

This issue has been marked as "Question" and has seen no recent activity. It has been automatically closed for house-keeping purposes.