reactjs - 对象数组类型声明中的打字稿可为空的键
问题描述
我正在使用 Typescript 编写 React 组件。目前我将道具的类型定义为 Typescript type
。这是一个例子:
type Props = {
id: number //required
name: string | null //optional
}
type ParentProps = Array<Props>
let props:ParentProps = [
{
id:5,
name:"new"
},
{
id:7,
}
]
//Gives error: Property 'name' is missing in type '{ id: number; }' but required in type 'Props'
在这种情况下,我希望type
ParentProps
只是type
Props
. 在实践中,可为空的 name 键适用于类型为 的单个对象Prop
。当声明一个ParentProps
this 类型的对象时,它给出了上面的代码片段。
为了与更简单的组件保持一致,我宁愿继续使用type
来定义组件道具,而不是接口。有人对如何声明类型以定义允许某些空键的类型对象数组有任何建议吗?
谢谢你。
解决方案
如何Props
通过以下方式定义:
type Props = {
id: number
name?: string | null
}
要不就
type Props = {
id: number
name?: string
}
此外,如果您想Props
保持定义不变,您可以更改type ParentProps
:
type ParentProps = Array< Omit<Props, "name"> & { name?: string|null } >
推荐阅读
- javascript - 如何使用 javascript 重新着色 Cordova 中的按钮
- javascript - 无法调用 JS 函数:语法错误或眼睛过于交叉?
- http - JMeter:用户定义的 Cookie 用于请求的目的
- python - Python Discord Bot '事件循环已关闭'
- python - Statsmodels VARMAX:具有多个内生变量的置信/预测区间
- javascript - 在 FlatList 内 2 到 5 秒后 React Native 可触摸不透明度按下
- linux - 如何为 ptrace 子设置 LD_PRELOAD 环境变量
- android - 字体系列在 Android 11 (api 30) 中不起作用
- visual-studio-code - 如何检查是否使用 Inno Setup 安装了 Visual Studio Code?
- javascript - 使用 window.open() 函数在 JavaScript 和 JSP 文件之间共享数据的问题