[英]typescript 3.0 and react defaultProps
If I have a prop defined like this: 如果我有一个像这样定义的道具:
interface Props {
Layout?: LayoutComponent;
}
Then if I supply defaultProps on on a ClassComponent
: 然后,如果我在ClassComponent
上提供defaultProps:
class MyComp extends React.Component<Props> {
static defaultProps: Pick<Props, 'Layout'> = {
Layout: ({ children }) => <>{children}</>
};
}
Typescript does not pickup the fact that it cannot be undefined: Typescript不会接受无法定义的事实:
render() {
const { previousLocation, data } = this.state;
const { location, Layout } = this.props;
const initialData = this.prefetcherCache[location.pathname] || data;
return (
<Layout> // JSX element type 'Layout' does not have any construct or call signatures.
<Switch>
It should never be undefined because of the defaultProps
. 由于defaultProps
永远不要取消定义它。 Typescript does not pick this up. 打字稿不接受。
Is there anyway of letting the compiler know that it cannot be undefined? 无论如何,有没有让编译器知道它不能被未定义?
TL;DR do not define Layout
prop as optional, typescript will handle it on its own. TL; DR并未将Layout
属性定义为可选属性,打字稿将自行处理。
Internally Layout
prop shouldn't be optional as it is always defined due to the defaultProps
: 在内部Layout
属性不应该是可选的,因为由于defaultProps
,它总是被定义的:
interface Props {
Layout: LayoutComponent;
}
For external users any prop that has a default prop is transformed to be optional by LibraryManagedAttributes
对于外部用户,具有默认属性的任何属性都可以通过LibraryManagedAttributes
转换为可选LibraryManagedAttributes
This helper type defines a transformation on the component's Props type, before using to check a JSX expression targeting it; 在用于检查针对它的JSX表达式之前,此辅助程序类型定义了组件的Props类型的转换。 thus allowing customization like: how conflicts between provided props and inferred props are handled, how inferences are mapped, how optionality is handled, and how inferences from differing places should be combined 因此可以进行自定义,例如:如何处理提供的道具与推断的道具之间的冲突,如何映射推理,如何处理可选性以及应如何组合来自不同地方的推理
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.