繁体   English   中英

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

[英]Typescript, conditional type based on the value of a string literal type

我对如何基于预定义的字符串文字为打字稿定义条件类型有些困惑

这是一个样机/示例,可以帮助解释对于一些背景知识,用户应该标记图像中的数据,目前只有两种类型的东西可以标记(例如,假设其pedestriansvehicles ),将来可能会更多。

在我的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[] }
    });

演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM