javascript - 传递给组件时打字稿混乱
问题描述
我对 Typescript 很陌生,但想更好地了解其中的来龙去脉。
假设我查询或获取一些以这种形式返回的数据
{
data: {
edges: {
node: {
id: '123',
label: 'test',
seo: {...}
etc...
}
}
}
}
当我将它传递给页面、组件等时(使用 Nextjs),由于解构和其他道具,我似乎必须为每个组件稍微添加这些类型。
例如,
const Home = (props: QueryResult) => ... // QueryResult taking the shape of the above object
然后,在从以下位置接收所有数据的 Layout 组件中Home
:
const Layout = ({ children, data, isPost }: DefaultProps)
另一轮声明,这次包括 children 和 isPost。我编写了另一个接口,在其中引用Home
文件中的 QueryResult。
现在,Layout 有一个 SEO 组件,它接收data.edges.node.seo
,还有另一个类型声明来描述所有 Seo 类型等。我希望它变得清楚我的目标。
我错过了什么吗?有没有更简洁的方法来做到这一点,例如一次编写一个更大的接口,然后在需要的地方借用某些类型?
您如何防止必须一直声明和重复类型?
解决方案
有点不清楚您在做什么,因为我没有看到示例和Home
您提到的 1:1。
如果您为需要接受作为参数或返回的所有数据声明类型或接口,请自下而上构建“顶层”,您的子组件只需使用您已声明的较小类型。没有重复。
type seoType = { /* stuff */ };
type nodeType = {
id: string;
label: string;
seo: seoType;
};
type dataType = {
edges: {
node: nodeType;
}
};
type topLevelType = {
data: dataType;
}
const topLevel: topLevelType = {
data: {
edges: {
node: {
id: '123',
label: 'test',
seo: { /* stuff */ }
}
}
}
}
您可以使用interface
而不是type
基于偏好或编码标准。
推荐阅读
- python - Clips Beginner:在 python 和 clipspy 的 clips 规则中添加常规 exp 或任何替代选择 *
- linux - 全新操作系统升级上的 MariaDb 无法运行,也无法访问旧数据库
- r - 如何在多面和分组的ggplot中着色条
- r - 在 R 中对列的一个大子集进行平方
- javascript - 如何在javascript中验证卡到期的未来日期
- onflow-cadence - 错误:受限类型不符合限制类型
- java - 'enableDefaultTyping(com.fasterxml.jackson.databind.ObjectMapper.DefaultTyping)' 在 RedisConfig 中已弃用
- c - 从函数返回结构后,文件删除和重命名不起作用
- android - Android平台makefile(Android.bp),如何使用kotlin @Parcelize注解创建aidl文件?
- mysql - 从 Drupal 7 迁移博客数据,结合两个 select 语句并创建输出表