英文:
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 = 'Test' }: TProps) => <div>{item}</div>;
export default Component;
// ...
<Parent>
<Component /> {/* skipping prop will default in 'Test' */}
</Parent>
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).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论