Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

import in react-scripts react-app-env.d.ts breaks tsc build

Tags:

typescript

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?

like image 967
dagda1 Avatar asked Jun 25 '19 10:06

dagda1


1 Answers

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.

like image 159
Titian Cernicova-Dragomir Avatar answered Nov 16 '22 06:11

Titian Cernicova-Dragomir