Search code examples
reactjstypescriptcreate-react-app

create-react-app typescript global.d.ts file doesn't work


I've got my global.d.ts file in src folder like this

declare global {
  interface Window {
    config: {
      url: string;
    };
  }
}

Then somewhere in my components do

window.config = 'x';

And ts shows this error

Error:(10, 22) TS2339: Property 'config' does not exist on type 'Window'.

create-react-app is used for this app.

"react-scripts": "3.0.1",
"typescript": "3.5.3"

This is how tsconfig.json looks like

{
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "preserve"
  },
  "include": [
    "src"
  ]
}

Solution

  • Provided your .d.ts file doesn't import or export anything, you can omit the declare global block.

    You will need to make sure this file is either in an @types directory, or that you have configured your typeRoots to include the directory for your type declarations e.g.

    {
      "compilerOptions": {
        "typeRoots": [
          "./node_modules/@types/",
          "./custom/path/to/declarations/"
        ]
      }
    }
    

    Some more info about this can be found here.