什么是TypeScript的字符串索引签名

120 阅读1分钟

可选属性

interface SquareConfig {
  color?: string;
  width?: number;
}

function createSquare(config: SquareConfig): {color: string; area: number} {
  let newSquare = {color: "white", area: 100};
  if (config.color) {
    newSquare.color = config.color;
  }
  if (config.width) {
    newSquare.area = config.width * config.width;
  }
  return newSquare;
}

let mySquare = createSquare({color: "black"});

可选属性的优点在于,可以捕获引用了不存在的属性时的错误。 比如,我们故意将 createSquare里的color属性名拼错,就会得到上图的错误提示。

如果消费这个函数时传入的对象字面量参数也不包含color属性:

同样会报错:

即使使用类型断言也不行:

错误消息:

Conversion of type ‘{ colour: string; width: number; }’ to type ‘SquareConfig’ may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to ‘unknown’ first.
Property ‘color’ is missing in type ‘{ colour: string; width: number; }’ but required in type ‘SquareConfig’.

17 let mySquare = createSquare({ colour: “red”, width: 100 } as SquareConfig);

解决办法是使用字符串索引签名,并且将color属性加上问号修饰,使其变成optional:

第四行[propName:string]:any的含义是,SquareConfig可以有任意数量的属性,并且只要它们不是color和width,那么就无所谓它们的类型是什么。

要获取更多Jerry的原创文章,请关注公众号"汪子熙":