1

I found that function accept a value which has different type with argument in typescript.

type A = { name: string, age: number };
type B = { name: string, age: number, hobby: 'cleanup' | 'pingpong' }

function test(t: A) {
    console.log(t);
}

const a: A = { name: 'yoon', age: 28 };
const b: B = { name: 'taetae', age: 25, hobby: 'cleanup' };

test(a); // OK
test(b); // OK
test({ name: 'yoon', age: 28 }); // OK
test({ name: 'yoon', age: 28, hobby: 'pingpong' }); // ERROR. Why?

I want to know why test(b) is OK but test({ name: 'yoon', age: 28, hobby: 'pingpong' }) is not.

Edit

In what case this policy (excess property check) is useful ?

Byeongin Yoon
  • 3,233
  • 6
  • 26
  • 44
  • 2
    Does this answer your question? [Why can I avoid excess property check in typescript just by passing a reference to an object to a function rather than the object in its literal form?](https://stackoverflow.com/questions/52852278/why-can-i-avoid-excess-property-check-in-typescript-just-by-passing-a-reference) – kaya3 Oct 09 '22 at 14:26
  • Object literal may only specify known properties, and 'hobby' does not exist in type 'A'. – Zahid Hasan Oct 09 '22 at 14:27
  • @kaya3 thanks, but it's not. Would you please give me some example why this decision is better ? – Byeongin Yoon Oct 09 '22 at 14:38
  • @ByeonginYoon That is explained in the answers to the linked question. What is the difference between your question and the linked one? The answer here written by ghybs says the same thing as my answer to the linked question, even. – kaya3 Oct 09 '22 at 14:39
  • @kaya3 yes, question is same. And "Their logic might be like this: if you have a variable, then it may come from some third party and there is not much you can do with it" is helpful answer,,but I want to know more specific example where excess property check policy is useful. – Byeongin Yoon Oct 09 '22 at 14:49
  • [^](https://stackoverflow.com/questions/74005329/why-does-typescript-treat-named-type-and-literal-type-differently#comment130669199_74005329) @ByeonginYoon Check this duplicate: [How excess property check helps?](https://stackoverflow.com/q/50143250/438273) – jsejcksn Oct 09 '22 at 15:29

1 Answers1

0

This is the effect of excess property check, but which works only on object literal, as in your last case.

The rationale for checking only in this case is simple: because the object cannot be used for any other usage (since it is not assigned to a variable that you can re-use), it is unlikely that you would purposely add extra useless properties. Therefore they are likely typos, or hints that you mistake the value for something else.

Whereas in the case of test(b), it is common practice to pass data that actually contains more properties than strictly required.

ghybs
  • 47,565
  • 6
  • 74
  • 99