打字稿对象文字

时间:2020-06-27 18:00:38

标签: typescript object interface literals behavior

https://www.typescriptlang.org/docs/handbook/interfaces.html包含以下示例:

interface LabeledValue {
  label: string;
}

function printLabel(labeledObj: LabeledValue) {
  console.log(labeledObj.label);
}

let myObj = { size: 10, label: "Size 10 Object" };
printLabel(myObj);

但是,如果我将对象文字传递给printLabel而不是myObj,就像这样:

printLabel({ size: 10, label: "Size 10 Object" })

然后我得到一个错误

>  error TS2345: Argument of type '{ size: number; label: string; }' is
> not assignable to parameter of type 'LabeledValue'.   Object literal
> may only specify known properties, and 'size' does not exist in type
> 'LabeledValue'.
> 
> 11 printLabel({ size: 10, label: "Size 10 Object" });

这是为什么?为什么这种行为不同?

1 个答案:

答案 0 :(得分:0)

As { size: 10, label: "Size 10 Object" } 是一个对象字面量。

当涉及到 ts 对象文字是否可分配给另一个时,它将比较整个属性。在这里,标签是不可接受的。