#weird problem with spread operator behavior?

23 messages · Page 1 of 1 (latest)

thorny valve
#

I guess the picture speaks for itself. Why doesn't the second example show any errors even tho clearly wrong property was passed? Can it be fixed?

cunning citrusBOT
#
frozen 麦#9514

Preview:```ts
type Hello = {
some_prop?: string
}

const wrongProperty = {
wrong_property: "123",
}

function hello(hello: Hello) {}

hello({...wrongProperty})
hello({...wrongProperty, some_prop: "asd"})```

vivid lodge
#

excess properties are allowed in some contexts, i guess spreading is one of them

#

looks like there's an issue for that

sacred juniper
#

so,

type Hello = {
  some_prop?: string
}

is a subset of the {} type

where {} isn't an empty object, it's a "thing" where I can access properties. so defining an object type says "look for at least these properties, but if it contains other properties that's fine"

vivid lodge
#

literals shouldn't have excess properties:

cunning citrusBOT
#
function fn(x: { k: string }) {}
fn({ n: "" })
//   ^^^^^
// Argument of type '{ n: string; }' is not assignable to parameter of type '{ k: string; }'.
//   Object literal may only specify known properties, and 'n' does not exist in type '{ k: string; }'.
#
ZachWasTaken#3603

Preview:```ts
type Hello = {some_prop: string}

const wrongProperty = {wrong_property: "123"}

function hello(hello: Hello) {}
hello(Object.assign({some_prop: ""}, wrongProperty))```

vivid lodge
#

but the spread gets around that incorrectly

vivid lodge
# cunning citrus

this is a demonstration of the correct behavior of object values allowing excess properties

#

but object literals specifically should not

thorny valve
#

damn so I guess the only way to do this right now is to write all the props individually?

vivid lodge
#

do what exactly?

thorny valve
#

make it so that props that don't belong are not allowed

vivid lodge
#

i guess, yeah

#

or maybe the spread makes ts not use the object literal rules and that's expected, but don't see any comments of the sort on the issue

sacred juniper
#
type K = { k: string }
function fn(x: K) {}
const wrong = { n: "", k: '' }
fn(wrong)
#

i see what you are saying chris

#

it works the way you'd expect if you provide a literal directly to the function

thorny valve
#

!resolved