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"
]
}
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.
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.
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.
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 {}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With