无法使用 Typescript (TS) 中的键访问对象值
Can't access object values using keys in Typescript (TS )
我有一个像这样的简单对象:
export const daysOfTheWeek = {
0: "Sunday",
1: "Monday",
2: "Tuesday",
3: "Wednesday",
4: "Thursday",
5: "Friday",
6: "Saturday",
};
我正在尝试使用像这样的变量来访问它:
const checkDay = (dayIndex: number):void => {
console.log(daysOfTheWeek[dayIndex]) // error happens here
};
我希望记录 "Sunday"
,但是我收到不断弹出的错误:
Element implicitly has an 'any' type because expression of type 'number' can't be used to index type '{ 0: string; 1: string; 2: string; 3: string; 4: string; 5: string; 6: string; }'.
No index signature with a parameter of type 'number' was found on type '{ 0: string; 1: string; 2: string; 3: string; 4: string; 5: string; 6: string; }'.ts(7053)
关于如何解决这个问题有什么建议吗?
您需要告诉 TypeScript dayIndex: number
实际上不仅仅是一个数字,而是 daysOfTheWeek
键之一。
const checkDay = (dayIndex: keyof typeof daysOfTheWeek):void => {
console.log(daysOfTheWeek[dayIndex])
};
如果你做不到,那么你必须在函数内部缩小范围
const checkDay = (dayIndex: number):void => {
if (dayIndex !== 1 && dayIndex !== 2 ...) {
throw new Error('Not a day of the week');
}
console.log(daysOfTheWeek[dayIndex])
};
或在检查范围后声明它:
const checkDay = (dayIndex: number):void => {
if (!Number.isInteger(dayIndex) || dayIndex < 0 || dayIndex > 6) {
throw new Error('Not a day of the week');
}
console.log(daysOfTheWeek[dayIndex as keyof typeof daysOfTheWeek])
};
我有一个像这样的简单对象:
export const daysOfTheWeek = {
0: "Sunday",
1: "Monday",
2: "Tuesday",
3: "Wednesday",
4: "Thursday",
5: "Friday",
6: "Saturday",
};
我正在尝试使用像这样的变量来访问它:
const checkDay = (dayIndex: number):void => {
console.log(daysOfTheWeek[dayIndex]) // error happens here
};
我希望记录 "Sunday"
,但是我收到不断弹出的错误:
Element implicitly has an 'any' type because expression of type 'number' can't be used to index type '{ 0: string; 1: string; 2: string; 3: string; 4: string; 5: string; 6: string; }'.
No index signature with a parameter of type 'number' was found on type '{ 0: string; 1: string; 2: string; 3: string; 4: string; 5: string; 6: string; }'.ts(7053)
关于如何解决这个问题有什么建议吗?
您需要告诉 TypeScript dayIndex: number
实际上不仅仅是一个数字,而是 daysOfTheWeek
键之一。
const checkDay = (dayIndex: keyof typeof daysOfTheWeek):void => {
console.log(daysOfTheWeek[dayIndex])
};
如果你做不到,那么你必须在函数内部缩小范围
const checkDay = (dayIndex: number):void => {
if (dayIndex !== 1 && dayIndex !== 2 ...) {
throw new Error('Not a day of the week');
}
console.log(daysOfTheWeek[dayIndex])
};
或在检查范围后声明它:
const checkDay = (dayIndex: number):void => {
if (!Number.isInteger(dayIndex) || dayIndex < 0 || dayIndex > 6) {
throw new Error('Not a day of the week');
}
console.log(daysOfTheWeek[dayIndex as keyof typeof daysOfTheWeek])
};