React + TypeScript在组件之前声明类型与在组件之后声明类型的区别

huangapple go评论63阅读模式
英文:

React+Typescript declare type before component vs after component

问题

以下是您要翻译的内容:

我对TypeScript还不熟悉,我看到一些项目在组件之前声明类型,而有些项目在组件之后声明类型,我能知道它们之间有什么区别吗?

export type TProps = {
    item: string;
}
export default function Component({item}: TProps) {
}
vs

```typescript
export default function Component({item}: TProps) {
}

export type TProps = {
    item: string;
}

这两种代码都能运行,哪一种更好,为什么呢?

找不到任何关于这个的文章。

谢谢您。

英文:

I am new to typescript, I saw some projects declaring the type before component and some of them declare after the component, may I know what are the differences?

export type TProps = {
    item: string;
}
export default function Component({item}: TProps) {
}

vs

export default function Component({item}: TProps) {
}

export type TProps = {
    item: string;
}

both of the code are able to run, which one is better and why?

couldn't find any article about this.

Thank you.

答案1

得分: 1

这与在JavaScript中可以在初始化之前调用函数的情况相同。

这只取决于开发者如何编写types

英文:

This is the same thing just like in JavaScript we can call function before initialisation.

It's just depends on developer who he can write the types .

答案2

得分: 1

在使用类型定义组件的 props 时,我倾向于将其放在组件之前。我之所以这样做是为了提高可读性,这样我可以快速查看组件接受哪些参数。

最终取决于个人偏好,但出于可读性考虑,我喜欢将其保持在顶部。

英文:

When using types for props specifically, I tend to put it before the component. I do this for readability so I can quickly see what the component takes for parameters.

Ultimately it comes down to preference, but for readability sake, I like to keep it at the top.

答案3

得分: 1

我喜欢将类型放在上面或单独的文件中,也许使用接口,但在你的情况下,可以像这样:

type TProps = {
  item?: string;
};

const Component = ({ item = 'Test' }: TProps) => <div>{item}</div>;

export default Component;
// ...
<Parent>
  <Component /> {/* 省略 prop 将默认为 'Test' */}
</Parent>

此外,我真的很喜欢组件的箭头函数是多么紧凑和整洁!(现在不需要 FC,因为defaultProps可以通过默认参数值来实现)。

英文:

I like types above or in a separate file and maybe interface but in your case, something like this:

type TProps = {
  item?: string;
};

const Component = ({ item = &#39;Test&#39; }: TProps) =&gt; &lt;div&gt;{item}&lt;/div&gt;;

export default Component;
// ...
&lt;Parent&gt;
&lt;Component /&gt; {/* skipping prop will default in &#39;Test&#39; */}
&lt;/Parent&gt;

Also I really like how compact and neat arrow functions for components are! (no FC required nowadays because defaultProps can be done through default param values of the props).

huangapple
  • 本文由 发表于 2023年7月13日 22:28:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/76680524.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定