如何从未知数据创建对象,该数据将是几种可能的类型之一?

时间:2019-02-04 13:51:09

标签: typescript

我正在从服务器获取数据。

const response = await request() as RecordingGetChannelData

此数据可以是三种类型之一。

export type RecordingGetChannelData = (
    RecordingGetChannelDataAnalogValues | 
    RecordingGetChannelDataGpiAndRxChannels | 
    RecordingGetChannelDataValueObject
);
export type RecordingGetChannelDataAnalogValues = {
    data_type: 'analog';
    timestamp: number;
    interval: number;
    values: number[];
    value: string;
};
export type RecordingGetChannelDataGpiAndRxChannels = {
    data_type: 'log';
    values: number[];
    value: string;
};
export type RecordingGetChannelDataValueObject = {
    timestamp: number;
    value: string;
};

从这个response我想创建一个对象channelData,它是三种类型之一

export type ChannelData = (
    ChannelDataAnalogValues | 
    ChannelDataGpiAndRxChannels | 
    ChannelDataValueObject
);
export type ChannelDataAnalogValues = {
    data_type: 'analog';
    timestamp: number;
    interval: number;
    values: number[];
    value: string;
};
export type ChannelDataGpiAndRxChannels = {
    data_type: 'log';
    values: number[];
    value: string;
};
export type ChannelDataValueObject = {
    timestamp: number;
    value: string;
};

我该怎么做?

这是我的最佳尝试,但不起作用:

let channelData = {};
if (response['data_type']) channelData.dataType = response['data_type'];
if (response['timestamp']) channelData.timestamp = response['timestamp'];
if (response['interval']) channelData.interval = response['interval'];
if (response['values']) channelData.values = response['values'];
if (response['value']) channelData.value = response['value'];

PS:我仍然不太了解何时应该使用类型vs接口,因此,如果接口更适合此类任务,那么我就不会反对使用它。

0 个答案:

没有答案