我正在尝试将 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/