0

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 Answers1

2

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.

Herrington Darkholme
  • 5,979
  • 1
  • 27
  • 43