1

CodeSandbox: https://codesandbox.io/s/staging-tree-i8uem?file=/src/index.ts

I have a function that takes an object param of a certain type.

interface MY_INTERFACE {
  PROP_A: string;                  // IN MY REAL CASE, THESE ARE NOT STRINGS
  PROP_B: string;
  PROP_C: string;
  PROP_D: string;
}

type OBJECT_PARAM_TYPE = {
  [key in keyof MY_INTERFACE]: string;
};

The object type OBJECT_PARAM_TYPE must have all the properties that are present in MY_INTERFACE and a string as a value.

The function I'm testing it with:

function someFunction(x: OBJECT_PARAM_TYPE): OBJECT_PARAM_TYPE {
  return x;
}

I'm getting different results when I'm passing the object as a variable, or an object literal.

TEST 1

Passing an object with an extra property PROP_E.

enter image description here

TEST 1 - Result

The code result1 that passses the object as a variable, does not trigger any errors.

Only the code result2 that passes the object literal is triggering the error for the extra property.

Why is that?

TEST 2

Passing an object with a missing property PROP_D.

enter image description here

TEST 2 - Result

Both codes show errors for the missing property PROP_D, which was the expected behavior for this test.


QUESTION

Why Typescript will not trigger the error for the extra property when I'm passing the object as a variable in TEST 1 ?

CodeSandbox: https://codesandbox.io/s/staging-tree-i8uem?file=/src/index.ts

cbdeveloper
  • 27,898
  • 37
  • 155
  • 336
  • Looks similar to https://stackoverflow.com/questions/52852278/why-can-i-avoid-excess-property-check-in-typescript-just-by-passing-a-reference – Serhii Yukhnevych Aug 13 '20 at 10:42

0 Answers0