TypeScript Revaluate default props behavior in JSX functional components

xwbd5t1u  于 2个月前  发布在  TypeScript
关注(0)|答案(3)|浏览(30)

关于将默认初始化器作为功能组件类型检查的一部分的识别,我认为问题$x_{1e0f1}^{x}$和$x_{1e1f1}^{x}$应该根据$x_{1e2f1}^{x}$以及defaultProps可能被弃用的情况,以及这两个问题本身的优点重新评估。

TypeScript版本: $3.7.5$

搜索词:

默认属性,功能组件,JSX,React

代码

查看问题$x_{1e3f1}^{x}$和$x_{1e4f1}^{x}$

预期行为:

查看问题$x_{1e5f1}^{x}$和$x_{1e6f1}^{x}$

实际行为:

查看问题$x_{1e7f1}^{x}$和$x_{1e8f1}^{x}$

Playground链接:

查看问题$x_{1e9f1}^{x}$和$x_{1e10f}^{x}$

相关问题:

问题$x_{1e11f}^{x}$和$x_{1e12f}^{x} = D$

zbsbpyhn

zbsbpyhn1#

这相当开放-你心里想的重新评估是什么?

abithluo

abithluo2#

Whoa.. that was fast. Thank you for that.
Both issues were closed on a "working as intended" basis (although only #32402 was labelled). Given the following code extracted from #31247 :

interface Props {
  name: string;
  optional: string;
}
const Component = ({ name, optional = "default" }: Props) => (
  <p>{name + " " + optional}</p>
);
const Test = () => <Component name="test" />;

IMHO it is safe to say that both, the "Component" function definition and the "Props" interface agree that "optional" should not be undefined. Even if rejecting "Test" definition is really working as intended, it is at least a bit surprising.
Although there are workarounds, including using "defaultProps", I believe it is undesirable to have to change a theoretically type safe code only to satisfy the type checker.
Now, since #34547 deals with, among other things, the possible deprecation of "defaultProps", it seemed like a good opportunity reevaluate supporting default initializers as an alternative, and a much less surprising solution, to default props on functional components.
Sorry for the long reply.
Regards

相关问题