如何将收到的字符串转换为枚举
我正在从文件中接收一些JSON对象,我想将一些字段解析为预定义的值。
import jobsRaw from '../../data/jobs.json';
我创建了一种描述我对象的类型,但是我希望 status 只有我的预定义值,如果我可以定义后返回值。
export type Job = {
type: string;
id: string;
status: JobStatus;
warehouseId: string;
relatedCell: string;
relatedDocument: string;
partnerName: string;
potatoType: string;
relatedBoxes: string[];
boxCount?: number;
createdAt: string;
completedAt: string;
};
这是我尝试使用的映射:
const jobs: Job[] = jobsRaw.map((job: Job) => ({
...job,
status: JobStatus[job.status],
boxCount: job.relatedBoxes.length,
}));
我想创建某种JobStatus类型,我可以用它来解析我收到的字符串值。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果我必须实施此功能,我会选择检查数据是否是正确的
JobStatus
。也许类似的事情:使用这种方法,您甚至可以在下面使用Map Iterator中使用其他类型的类型来更好地表示“原始”数据,因为类型的谓词会将
job.status
作为适当的JobStatus
当它返回true时。我还在job
中进行了boxcount
强制性,并从jobRaw
中将其删除,您不需要使其可选。If I had to implement this I would go for a type predicate to check if the data is a proper
JobStatus
. Maybe something like this:With this approach you could even use a different type in map iterator like below to better represent the "raw" data because the type predicate will cast
job.status
as a properJobStatus
when it returns true. I've also madeboxCount
mandatory inJob
and removed it fromJobRaw
, by doing like this you won't need to make it optional.