打字稿字符串到枚举转换错误

时间:2019-10-17 16:00:23

标签: typescript typescript-typings

我需要将字符串(UrlStatus)转换为enum(Status)。

export enum Status {
  available,
  inProgress
}

export type UrlStatus = 'available' | 'inprogress';

// something wrong here
export const UrlStatusToStatus: { [UrlStatus]: Status } = {
  available: [Status.available],
  inprogress: [Status.inProgress]
}

尝试使用UrlStatusToStatus[status] //status's type is UrlStatus

时出现此错误
Element implicitly has an 'any' type because expression of type 'UrlStatus' can't be used to index type '{}'.
  Property 'available' does not exist on type '{}'.

我在做什么错了?

1 个答案:

答案 0 :(得分:0)

您的语法略有偏离:

enum Status {
  available = 1,
  inProgress = 2
};

type UrlStatus = 'available' | 'inprogress';

const UrlStatusToStatus: { [key in UrlStatus]: Status } = {
    available: Status.available,
    inprogress: Status.inProgress
};

console.log(UrlStatusToStatus['inprogress']);

输出:

  

2