Tslint error when using createBrowserHistory() from @types/history
Asked Answered
H

1

8

I am importing the @types/history and using the createBrowserHistory() function it provides, in my React application.

I get a tslint error saying,

ERROR in C:/Users/eshan/my-website/src/App.tsx
ERROR in C:/Users/eshan/my-website/src/App.tsx(13,11):
typedef: expected variable-declaration: 'history' to have a typedef

I did look around a bit, but all of the attempts to mitigate this seem to be aimed at removing the tslint rules by doing /* tslint:disable */. I would like to add type support, and fix it instead.

import * as React from 'react';
import { Router, Route, Switch } from 'react-router-dom';
import { createBrowserHistory } from 'history';
import './App.css';

class App extends React.Component {
  public render(): JSX.Element {
  const history = createBrowserHistory();

  return (
    <div className='App'>
      <Router history={history}>
        <Switch>
          <Route exact path='/' component={Landing}/>
          <Route exact path='/Home' component={Home}/>
        </Switch>
      </Router>
    </div>
    );
  }
}

export default App;
Hamil answered 3/2, 2019 at 3:13 Comment(0)
C
7

Your issue isn't with the @types/history library at all. It's that the typedef rule is configured in your tslint.json settings to require type definitions in places including your history variable.

This code would likely also exhibit the TSLint complaint:

const createMyHistory = () => ({
    someMember: "someValue",
});

const history = createMyHistory();

..because history doesn't have an explicit type definition.

Here are two ways you could resolve the error without a // tslint:disable-next-line:

Edit: just to add more visibility to what's in the comments below, there are two types/interfaces named History at play here. One is the globally defined one that comes with DOM typings. Another is the one that's defined in @types/history. It's unfortunately confusing that they both have the same name. If you're seeing errors about History<any> not being compatible with History, add History to your import from history:

import { createBrowserHistory, History } from 'history';

That will make your code refer to @types/history's version.

Christelchristen answered 3/2, 2019 at 19:47 Comment(2)
when I add an explicit type definition to the history variable, as you suggest in the last line, I get this compile time error. [ts] Type 'History<any>' is not assignable to type 'History'. Property 'scrollRestoration' is missing in type 'History<any>'.Hamil
Spooky. It might be that there are two types at play: one is the predefined global History, and the other is a type inside the @types/history definitions that also happens to be named History. It's a bit inconvenient how they're named the same thing. If you add History to your import from history, does the complaint go away?Christelchristen

© 2022 - 2024 — McMap. All rights reserved.