从函数返回的TypeScript'字符串'

时间:2020-08-14 16:40:40

标签: typescript

我有一个函数translateNumericDayToString,该函数返回带有日期名称的字符串(例如“ monday”):

export function translateNumericDayToString(day: number) {
  const days = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];
  return days[day];
}

我有一个json类型和以下代码:

type days = {
  sunday: {
    ...
  },
  monday: {
    ...
  },
}

currentDayIndex = 1
const currentDay: keyof typeof days = translateNumericDayToString(currentDayIndex);

我得到Type 'string' is not assignable to type '"monday" | "tuesday" | "wednesday" | "thursday" | "friday" | "saturday" | "sunday"''

当我更改为const currentDay: keyof typeof days = "monday"时,它可以正常工作。

为什么?正确的方法是什么?

1 个答案:

答案 0 :(得分:2)

使用as const(“常量声明”,在Typescript 3.4中引入)。照原样,Typescript看到一个字符串数组,并假定该数组是可变的。使用as const,Typescript可以正确地理解该数组是一个常量值列表。

export function translateNumericDayToString(day: number) {
  const days = ['sunday', /*...*/ 'saturday'] as const;
                                           // ^^^^^^^^
  return days[day];
}

// return type is now "sunday" | /* ... */ | "saturday"

typescript playground