Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"
  ]
}
like image 224
Hayk Safaryan Avatar asked Jul 20 '19 13:07

Hayk Safaryan


People also ask

Can we use TypeScript in Create React app?

If you're building a new app and using create-react-app , the docs are great: You can start a new TypeScript app using templates. To use our provided TypeScript template, append --template typescript to the creation command.

What is ENV D TS React?

The react-app-env. d. ts references the types of react-scripts , and helps with things like allowing for SVG imports. The additional recommendations come from the react-typescript-cheatsheet community and the explanations come from the Compiler Options docs in the Official TypeScript Handbook.

Do you need to import React in TypeScript?

For a very long time in React development, it was necessary to import React in your JavaScript or TypeScript files that used React components. It wasn't until React v17. 0, which was released in August of 2020, that React introduced a new transform feature that allowed its developers to not have to do this anymore.


2 Answers

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 {}
like image 78
Dana Woodman Avatar answered Sep 29 '22 12:09

Dana Woodman


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.

like image 33
JakeSidSmith Avatar answered Sep 29 '22 10:09

JakeSidSmith