reactjs - 使用 defaultProps 时 typescript 不发出枚举导入

标签 reactjs typescript enums

我正在尝试将 defaultProps 与具有 Enum prop 的组件一起使用。组件的 props 接口(interface)在另一个文件中定义,defaultProps 中分配的枚举值也是如此。

这工作正常,但是当我编译项目并检查 tsc 为组件生成的声明文件时,它正确地生成了 defaultProps 的类型,但是枚举没有 import 语句。

应用.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;

类型.tsx

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

export interface IAppProps {
    animal: AnimalEnum;
}

默认.ts

import { AnimalEnum } from "./types";

export const defaults = {
    animal: AnimalEnum.Cat
}

发出的文件 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 版本是 ^3.0.3

最佳答案

看起来像一个错误。我 reported it .作为解决方法,如果您在 defaultProps 字段上添加类型注释(即使它只是 {animal: typeof defaults.animal}),生成的声明文件似乎是有效。

关于reactjs - 使用 defaultProps 时 typescript 不发出枚举导入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52216570/

相关文章:

javascript - React组件声明中 'export'的作用是什么?

javascript - 每个附件我都需要附上pdf或word或jpg图标

swift - 如何使用单个 case 语句检查枚举的值及其关联的枚举值?

reactjs - 当我在 create-react-app 中输入 npm start 时如何指定自定义 URL

typescript - 用 Jest 模拟 typescript 界面

javascript - 在 typescript 中获取函数名称

typescript - "find all references"不起作用,除非相关文件打开

c# - 你会在长开关/枚举声明中使用区域吗?

c# - 通过用户输入扩展枚举

javascript - 从条件渲染的 JSX 内部调用类方法