ts中接口的可选属性是怎么检测的

现在有个案例

interface SquareConfig {
  color?: string,
  width?: number
}
function createSquare(config: SquareConfig): Square {
  let newSquare = {
    color: "red",
    width: 10,
  }
  if (config.color) {
    newSquare.color = config.color
  }
  if (config.width) {
    newSquare.width = config.width
  }
  return newSquare
}
let square1 = { width: 1 }
let square2 = { width: 1, name: "square" }
let square3 = { name: "square" }
createSquare(square1)
createSquare(square2)
createSquare(square3)

函数createSquare传入 square1、square2都没问题,传入square3就有报错信息
Type '{ name: string; }' has no properties in common with type 'SquareConfig',为什么
width和color不是可选吗,怎么只传入name属性就有问题呢,如果传入的是{}也没有问题。求教!!!

阅读 3.5k
1 个回答
interface SquareConfig {
  color?: string,
  width?: number
}

你的接口中并没有 name字段,你需要使用任意属性的方式

interface SquareConfig {
  color?: string,
  width?: number,
  [propName: string]: any
}

至于let square2 = { width: 1, name: "square" } 没有报错,这里引用文档中的解释:

还有最后一种跳过这些检查的方式,这可能会让你感到惊讶,它就是将这个对象赋值给一个另一个变量: 因为squareOptions不会经过额外属性检查,所以编译器不会报错。
let squareOptions = { width: 1, name: "square" };
let mySquare = createSquare(squareOptions);
上面的方法只在squareOptions和SquareConfig之间有共同的属性时才好用。 在这个例子中,这个属性为width。如果变量间不存在共同的对象属性将会报错。例如:
let squareOptions = { name: "square" };
let mySquare = createSquare(squareOptions);
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题