Partial<T> only works with inline values

荒凉一梦 提交于 2019-12-12 02:10:03

问题


Why does the code below behave like it does? Is it a bug in the TypeScript compiler or missing feature?

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!

I used TypeScript version 2.1.6


回答1:


What you are asking for is exact type, which is tracked here.

Currently TypeScript will only check excessive object keys for object literal, mainly for typo. After you bind a object to variable, TypeScript will not check excessive keys.

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

Partial is effectively add optional mark to the fields of your class.

So it does not report error for myValue3.



来源:https://stackoverflow.com/questions/42345580/partialt-only-works-with-inline-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!