#Object literal may only specify known properties scenario I can't understand.

7 messages · Page 1 of 1 (latest)

limber glen
#
function exact<T>(item: T): T { return item }
type Hello = { hello: string }

1.
exact<Hello>({ hello: "hello", world: "world" }) //error, world is not part of Hello

2.
const helloWorld = { hello: "hello", world: "world" } 
exact<Hello>(helloWorld) //no error

Why do these examples give different outcome?

sinful kettle
#

you no longer have an object literal being assigned to a type in the second case.

#

let's simplify the example a bit

type Hello = { hello: string };
type HelloWorld = { hello: string; world: string };

let hello: Hello;
let helloWorld: HelloWorld;
hello = { hello: "hello" };                        // works
hello = { hello: "hello", world: "world" };        // errors
helloWorld = { hello: "hello", world: "world" };   // works
hello = helloWorld;                                // works
#

case 1 in your example is basically the 2nd assignment there, while case 2 is the 3rd and 4th assignments

#

when you have an object literal being assigned to something that has a concrete type, that object literal must not have excess properties, ie properties that weren't specified in the type

but in other cases, excess properties are allowed, so polymorphism works
specifically, HelloWorld has all the required properties of Hello, and more properties, so HelloWorld is a subtype of Hello, it's more specific
thus, HelloWorld can be assigned to Hello

limber glen
#

Thanks!

ripe halo
#

!resolved