美文网首页
溢出属性检查

溢出属性检查

作者: 冰落寞成 | 来源:发表于2024-02-01 13:39 被阅读0次

在何处以及如何为对象分配类型可以在类型系统中产生差异。这方面的一个关键示例是溢出属性检查,它会在创建对象时更彻底地验证对象并在创建期间将其分配给对象类型。
例如

interface SquareConfig {
  color?: string;
  width?: number;
}
 
function createSquare(config: SquareConfig): { color: string; area: number } {
  return {
    color: config.color || "red",
    area: config.width ? config.width * config.width : 20,
  };
}
 
let mySquare = createSquare({ colour: "blue", width: 100 });

请注意,createSquare 的给定参数拼写为 colour 而不是 color。在普通的 JavaScript 中,这种事情会悄无声息地失败。

Argument of type '{ colour: string; width: number; }' is not assignable to parameter of type 'SquareConfig'.
Object literal may only specify known properties, but 'colour' does not exist in type 'SquareConfig'. Did you mean to write 'color'?

绕过这些检查实际上非常简单。最简单的方法是只使用类型断言:

interface SquareConfig {
  color?: string;
  width?: number;
  [propName: string]: any;
}
let mySquare = createSquare({ width: 100, opacity: 0.5 } as SquareConfig);

相关文章

网友评论

      本文标题:溢出属性检查

      本文链接:https://www.haomeiwen.com/subject/lgczodtx.html