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

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

React+Typescript declare type before component vs after component

问题

以下是您要翻译的内容:

  1. 我对TypeScript还不熟悉,我看到一些项目在组件之前声明类型,而有些项目在组件之后声明类型,我能知道它们之间有什么区别吗?
  2. export type TProps = {
  3. item: string;
  4. }
  5. export default function Component({item}: TProps) {
  6. }
  1. vs
  2. ```typescript
  3. export default function Component({item}: TProps) {
  4. }
  5. export type TProps = {
  6. item: string;
  7. }

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

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

谢谢您。

英文:

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?

  1. export type TProps = {
  2. item: string;
  3. }
  4. export default function Component({item}: TProps) {
  5. }

vs

  1. export default function Component({item}: TProps) {
  2. }
  3. export type TProps = {
  4. item: string;
  5. }

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

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

  1. type TProps = {
  2. item?: string;
  3. };
  4. const Component = ({ item = 'Test' }: TProps) => <div>{item}</div>;
  5. export default Component;
  6. // ...
  7. <Parent>
  8. <Component /> {/* 省略 prop 将默认为 'Test' */}
  9. </Parent>

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

英文:

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

  1. type TProps = {
  2. item?: string;
  3. };
  4. const Component = ({ item = &#39;Test&#39; }: TProps) =&gt; &lt;div&gt;{item}&lt;/div&gt;;
  5. export default Component;
  6. // ...
  7. &lt;Parent&gt;
  8. &lt;Component /&gt; {/* skipping prop will default in &#39;Test&#39; */}
  9. &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:

确定