I want to import types in a file that is generated by react-scripts.
I have created this minimal repo that shows the problem.
I have this so far:
// import * as React from 'react';
// import { MemoryHistory } from 'history';
// import { RenderResult } from 'react-testing-library';
interface Window {
env: any;
}
type ContextDefaultValue = [string, (val: string) => void];
/* global function for rendering with Router */
declare function renderWithRouter(ui: any, { route, history, }?: {
route?: string;
history?: any;
}): any;
If I uncomment any of the import statements and run tsc, then renderWithRouter is no longer in the global namespace and I get this error:
Cannot find name 'renderWithRouter'.
Can I not import types in .d.ts files?
Adding an import to a file makes it a module. So in a module if you declare an interface Window
it is declared local to that module.
If you want to use imports, but still keep the declarations global, you have two options:
Use declare global
import * as React from 'react';
import { History } from 'history';
import { RenderResult } from 'react-testing-library';
declare global {
interface Window {
env: any;
}
declare function renderWithRouter(ui: any, { route, history, }?: {
route?: string;
history?: History;
}): RenderResult;
}
Use import
types
interface Window {
env: any;
}
declare function renderWithRouter(ui: any, { route, history, }?: {
route?: string;
history?: import('history').History;
}): import('react-testing-library').RenderResult;
Either version will work, the declare global
is easier if you use a lot of types from other modules.
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