17

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"
  ]
}

3 Answers 3

33

A simpler approach would be to export an empty object from your global.d.ts, like so:

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

// Adding this exports the declaration file which Typescript/CRA can now pickup:
export {}
Sign up to request clarification or add additional context in comments.

1 Comment

Very nice zero-config approach.
14

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.

Comments

1

I encountered the same error, except in my case I want to declare my global types in a @types folder in my top-level directory.

I solved the error by adding the root to my tsconfig.json's include paths:

// in tsconfig.json

{
  "compilerOptions": {
    // ...
  },
  "include": [
    // ...
    "."   // adds root as an include path
  ]

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.