我对如何基于预定义的字符串文本为typescript定义条件类型有点拘泥。
这是一个有助于解释的模型/示例
对于一个小背景,用户应该标记来自图像的数据,目前只有两种类型的东西需要标记(对于本例,让我们说
pedestrians
和
vehicles
)未来可能会更多。
在我的Redux存储中,我存储来自API请求的数据(请求根据其中一种类型获取一组新的要标记的数据)。问题是,我得到的数据是不同格式的,这两种类型的东西可以用帧数组的值来标记aka帧数组或对象。
type ILabelingTypes = "pedestrians" | "vehicles"
一个框架像这样
interface IFrame {
url: string
orientation: number
// anything else related to a frame
}
API请求将是
/labeling/vehicles/new
以一个例子回答
{
// meta info about the labeling session
frames: IFrame[]
}
或
/labeling/pedestrians/new
以一个例子回答
{
// meta info about the labeling session
frames: Map<string, IFrame[]>
}
我现在面临的问题是,当我定义商店接口时,如何正确地键入
frames
关键是,这样我就不必到处检查就可以使用它,它是什么类型的数据?
interface ILabelingStore {
labelingType: ILabelingTypes
frames: // what do i put here?
}
意思是当我要呈现或使用这些数据时,我只想调用我知道存在的方法,这取决于
labelingType
在商店中定义
对于react组件端,当我要渲染帧时,我会构建一个要完成的帧队列,因此我需要知道数据在各自组件中的类型。
(这是我想要做的,而不是检查帧的类型)
// pedestrians component
componentDidMount() {
Object.entries(this.props.frames).forEach( (key, val) => this.queue.concat(val))
}
// vehicles component
componentDidMount() {
this.queue.concat(this.props.frames)
}