Why do subtypes need to be assigned to a variable before being used as a function argument?

It’s because when you use a “fresh” object literal (meaning one that hasn’t been assigned to a variable yet) in a place that expects a particular type, it’s often an error to add properties not mentioned in the type. So this is flagged as an error via excess property checking. It’s one of the few places where a type is treated as “closed” or “exact” (as requested in microsoft/TypeScript#12936 as opposed to “open”.

There are workarounds in the case where you don’t mean for excess property checks to happen. One is to add an index signature to the type of the n parameter so that all extra properties are acceptable:

function greet(n: Named & { [x: string]: unknown }) {
  console.log("Hello, " + n.name);
}
greet({ name: "Alice", location: "Seattle" }); // okay

Or, if you usually want such checking but just want to call greet() with that particular object literal, you can use a type assertion to avoid intermediate variables:

greet({ name: "Alice", location: "Seattle" } as Named); // okay

It’s up to you. Okay, hope that helps; good luck!

Leave a Comment