Typescript not emitting enum import when using defaultProps

Viewed 566

I am trying to use defaultProps with a component that has Enum prop. The props interface for the component is defined in another file and so is the enum value assigned in defaultProps.

This works fine but when I compile project and check the declaration file generated by tsc for the component, it generates the type for defaultProps correctly but the enum doesn't have the import statement.

App.ts

import * as React from 'react';
import './App.css';

import { defaults } from './defaults';
import { IAppProps } from './types';

import logo from './logo.svg';

class App extends React.Component<IAppProps> {
  public static defaultProps = {
    animal: defaults.animal
  }
  public render() {
    return (
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h1 className="App-title">Welcome to React</h1>
        </header>
        <p className="App-intro">
          To get started, edit <code>src/App.tsx</code> and save to reload.
        </p>
      </div>
    );
  }
}

export default App;

types.tsx

export enum AnimalEnum {
    Cat = "Cat",
    Dog = "Dog"
}

export interface IAppProps {
    animal: AnimalEnum;
}

defaults.ts

import { AnimalEnum } from "./types";

export const defaults = {
    animal: AnimalEnum.Cat
}

Emitted file App.d.ts

import * as React from 'react';
import './App.css';
import { IAppProps } from './types';
declare class App extends React.Component<IAppProps> {
    static defaultProps: {
        animal: AnimalEnum; //<---------AnimalEnum doesn't have import!
    };
    render(): JSX.Element;
}
export default App;

tsconfig.json

{
  "compilerOptions": {
    "baseUrl": ".",
    "outDir": "build/dist",
    "module": "esnext",
    "target": "es5",
    "lib": ["es6", "dom"],
    "sourceMap": true,
    "allowJs": false,
    "jsx": "react",
    "moduleResolution": "node",
    "rootDir": "src",
    "forceConsistentCasingInFileNames": true,
    "noImplicitReturns": true,
    "noImplicitThis": true,
    "noImplicitAny": true,
    "strictNullChecks": true,
    "declaration": true,
    "suppressImplicitAnyIndexErrors": true,
    "noUnusedLocals": true
  },
  "exclude": [
    "node_modules",
    "build",
    "scripts",
    "acceptance-tests",
    "webpack",
    "jest",
    "src/setupTests.ts"
  ]
}

typescript version is ^3.0.3

1 Answers

Looks like a bug. I reported it. As a workaround, if you add a type annotation on the defaultProps field (even if it's just {animal: typeof defaults.animal}), the generated declaration file seems to be valid.

Related