Partial<T> 仅适用于内联值

Partial<T> only works with inline values

为什么下面的代码会这样?它是 TypeScript 编译器中的错误还是缺少功能?

class MyType {
  constructor(public readonly value1: string, public readonly value2: number) {
  }  
}

function myFunction(props: Partial<MyType>): void {
  // Do something here    
}

myFunction({ }); // Compiles
myFunction({ value1: 'string', value2: 42 }); // Compiles
myFunction({ wrongValue: true }); // Compile error!!

const myValue1 = {};
const myValue2 = { value1: 'string', value2: 42 };
const myValue3 = { wrongValue: true };

myFunction(myValue1); // Compiles
myFunction(myValue2); // Compiles
myFunction(myValue3); // Compiles, but why?!? I expected this not to compile!

我使用的是 TypeScript 版本 2.1.6

您要的是精确类型,已跟踪here

目前 TypeScript 只会检查对象字面量的过多对象键,主要是针对拼写错误。将对象绑定到变​​量后,TypeScript 将不会检查过多的键。

规格:https://github.com/Microsoft/TypeScript/blob/02547fe664a1b5d1f07ea459f054c34e356d3746/doc/spec.md#3115-excess-properties

部分有效地为您的 class 字段添加可选标记。

所以它不会报告 myValue3 的错误。