reactjs - 用 typescript 构造一个通用接口
问题描述
我很难创建一个代表组件状态的接口。假设如下:
interface IFoo {
fooName: string;
fooValue: string | boolean | Array<string>
}
然后我们有以下对象:
const objOne: IFoo = {
fooName: 'objOneName',
fooValue: true
}
const objTwo: IFoo = {
fooName: 'objTwoName',
fooValue: ['a', 'b', 'c']
}
现在我们有一个包含这些对象的数组:
const myArray: IFoo[] = [objOne, objTwo];
现在在一个 React 组件中,我收到了 myArray 作为道具,需要为组件状态构造接口。
我需要一个新的接口来表示反应组件的状态,它应该如下所示:
interface myState {
someProp: string;
// The following values need to be dynamic. I don't know how many entries are there in the array
// in the is example: objOneName is the value of objOne[fooName] and it's type is the type of obj[fooValue]
objOneName: boolean,
objTwoName: Array<string>
}
解决方案
您可以创建以下通用道具
interface ArbitraryProps {
[key: string]: string | boolean | Array<string>
}
interface myState extends ArbitraryProps {
someProp: string;
}
我将其提取ArbitraryProps
为一个单独的接口,因为我想您想对通过它发送组件的道具进行类型检查。此外,这种方法可能太松散了,但这感觉就像我们只能通过重新思考这里的设计来获得高度......
推荐阅读
- javascript - 使用 WebKit 进行 JavaScript 操作 - 无法将卸载消息传递给 WebKit
- angular - Angular将一组数据从一个模块传递到另一个模块
- dataframe - 加入spark数据帧时如何添加多个条件
- php - 如何成功地将 %s 添加到我的 href 链接?
- arangodb - Foxx ArangoDB 更新数据
- fairseq - 我们是否应该期望 wav2vec 的性能优于 Microsoft STT
- python - 函数仅在直接从 jupyter 运行时使用多个进程
- python - 反向while循环python
- c++ - SDL_rect.h 给出 SDL_bool 警告
- python - 设置字典路径