我有一个函数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"
时,它可以正常工作。
为什么?正确的方法是什么?
答案 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"