我有一个反应项目,我正在转换从JS到TS。我遇到的一个问题是,TSX的反应是假设一个功能组件中定义的所有属性都是必需的道具。
// ComponentA.tsx
class ComponentA extends React.Component<any, any> {
render() {
/* Type '{ equalWidth: true; children: Element[]; }' is not assignable to type '{ children: any; className: any; equalWidth: any; }'.
* Property 'className' is missing in type '{ equalWidth: true; children: Element[]; }'.' */
return <ComponentB equalWidth />
}
}和
// ComponentB.js
const ComponentB = ({ children, className, equalWidth }) => {
return (...)
}有没有办法向TS发出信号,表明JSX组件道具都是可选的?
发布于 2017-08-25 00:58:23
一个最简单的选项是为您的可选道具设置一个默认值。例如,如果className是可选的,则可以将ComponentB.js更改为如下所示。
const ComponentB = ({ children, className="", equalWidth }) => {
return (...)
}另外,如果您解构函数体中的道具而不是签名,TS将不会抱怨输入。
const ComponentB = (props) => {
const { children, className, equalWidth } = props;
return (...)
}发布于 2017-07-31 16:29:13
假设ComponentB.js将作为TypeScript组件结束:
interface ComponentBProps {
children?: ReactNode;
className?: string;
equalWidth?: boolean;
}
const ComponentB = ({ children, className, equalWidth }: ComponentBProps) => {
//
};在所有属性都是可选的特殊情况下,您可以从接口上的每个属性中删除?并使用Partial<ComponentBProps>,但我想至少会有一些东西成为必需的支柱。
如果您想保持ComponentB.js的原样,那么另一种解决方案是创建一个类型定义文件:
import { ReactNode, StatelessComponent } from "react";
interface ComponentBProps {
children?: ReactNode
className?: string;
equalWidth?: boolean;
}
export const ComponentB: StatelessComponent<ComponentBProps>;如果您在这个目录中放置了与JavaScript文件相同的目录,并且名称为ComponentB.d.ts,那么您应该能够在TypeScript文件中导入ComponentB。
我编写定义的方式假设组件是一个名为export的,而不是默认的,即它像export const ComponentB一样在.js文件中导出。
(可能)工作示例:https://github.com/fenech/tsx-jsx
https://stackoverflow.com/questions/45420826
复制相似问题