Typescript 定义一个object,用for in时报错

1,106 阅读1分钟

定义一个object,用for in时报错

error->Element implicitly has an 'any' type because type 'xxxx' has no index signature.

代码如下:

interface DateFormat {
    'M+': number; // 月份
    'd+': number; // 日
    'h+': number; // 小时
    'm+': number; // 分
    's+': number; // 秒
    'q+': number; // 季度
    'S': number; // 毫秒
}
const o: DateFormat = {
  'M+': d.getMonth() + 1, // 月份
  'd+': d.getDate(), // 日
  'h+': d.getHours(), // 小时
  'm+': d.getMinutes(), // 分
  's+': d.getSeconds(), // 秒
  'q+': Math.floor((d.getMonth() + 3) / 3), // 季度
   'S': d.getMilliseconds(), // 毫秒
 };

for(let k in o) {
  console.log(o[k]); // error->Element implicitly has an 'any' type because type 'DateFormat' has no index signature.
 }

其实报错信息上已经比较明显了,需要个给定义的类型增加索引,做法如下

interface DateFormat {
    [index: string]: number;
}

解决问题