gpt4 book ai didi

reactjs - Typescript,基于字符串文字类型值的条件类型

转载 作者:搜寻专家 更新时间:2023-10-30 21:27:42 25 4
gpt4 key购买 nike

我对如何根据预定义的字符串文字为 typescript 定义条件类型有些困惑

这是一个帮助解释的模型/示例对于一些背景知识,用户应该从图像中标记数据,目前只有两种类型的东西要标记(对于这个例子来说它的行人车辆)在未来可能会更多。

在我的 Redux 存储中,我正在存储来自 API 请求的数据(请求获取一组新数据以根据其中一种类型进行标记)。问题是我获得的数据对于两种类型的事物采用不同的格式来标记帧数组或具有帧数组值的对象。

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)
}

最佳答案

您可以创建一个受歧视的联盟:

type ILabelingStore = ({
labelingType: "vehicles",
frames: IFrame[]
} | {
labelingType: "pedestrians",
frames: { [key: string]: IFrame[] }
});

Demo

关于reactjs - Typescript,基于字符串文字类型值的条件类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50589683/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com