简体   繁体   English

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

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

I'm a little stuck on how to define a conditional type for typescript based on a predefined string literal 我对如何基于预定义的字符串文字为打字稿定义条件类型有些困惑

This is a mockup / example to help explain For a little background, a user is supposed to label data from images, currently there are only 2 types of things to label (for this example lets say its pedestrians and vehicles ) potentially more in the future. 这是一个样机/示例,可以帮助解释对于一些背景知识,用户应该标记图像中的数据,目前只有两种类型的东西可以标记(例如,假设其pedestriansvehicles ),将来可能会更多。

In my Redux store I am storing data from an API request (request gets a new set of data to label based on one of these types). 在我的Redux商店中,我正在存储来自API请求的数据(请求会根据其中一种类型获取一组新的数据进行标记)。 The issue is the data that i get is in different formats for the two types of things to label aka array of frames or object with values that are frame arrays. 问题是我得到的数据是两种类型的东西的不同格式,以帧或对象的值来标记帧或数组的数组。

type ILabelingTypes = "pedestrians" | "vehicles"

A frame would look like this 框架看起来像这样

interface IFrame {
    url: string
    orientation: number
    // anything else related to a frame
}

The api requests would be /labeling/vehicles/new with an example response api请求为/labeling/vehicles/new并带有示例响应

{
    // meta info about the labeling session
    frames: IFrame[]
}

or /labeling/pedestrians/new with an example response /labeling/pedestrians/new带有示例响应)

{
    // meta info about the labeling session
    frames: Map<string, IFrame[]>
}

The issue I'm having now is when I define my store interface, how do i correctly type the frames key so that I don't have to check everywhere i go to use it what type of data it is? 我现在遇到的问题是,当我定义商店界面时,如何正确键入frames键,这样我就不必检查我要使用的所有数据类型了?

interface ILabelingStore {
    labelingType: ILabelingTypes
    frames: // what do i put here?
}

Meaning when i go to render or use this data I'd like to simply call methods that i know exist depending on the labelingType defined in the store 意思是当我去渲染或使用这些数据时,我想简单地调用我所知道的方法,具体取决于商店中定义的labelingType


For the React component side, when i go to render the frames I build a queue of frames to complete, so i need to know what type the data is in the respective component (This is what i would like to do instead of having to check the type of frames) 对于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)
}

You can create a discriminated union: 您可以创建一个有区别的联合:

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

Demo 演示

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

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