#type error absence?

27 messages · Page 1 of 1 (latest)

errant raven
#
function abc (d: {d:string} | null) {
    const aux = {a: 't', b: 1, c: false, ...(d && {d: 11})} // if d is null this expression ...(d && ..) does not compile, so why doesn't the typechecker complain here?
    aux
}

Why doesn't typescript complain here? When d is null the the expression reduces to ...false which is invalid syntax?

grim edge
#

@errant raven That's not invalid syntax in an object spread.

sterile flax
#

When d is null the the expression reduces to ...false
&& short-circuits to a value, not to a boolean, so it'd result in null

#

same for ||

frigid dune
halcyon templeBOT
#

@frigid dune Here's a shortened URL of your playground link! You can remove the full link from your message.

mishall8399#0

Preview:ts function test(value: boolean) { return {...(value || {})} }

sterile flax
frigid dune
#

Oh wait, it is because of boolean, null is fine

grim edge
#

Yeah, boolean is errored by TS (though it's allowed at runtime and just doesn't add anything to the object)

sterile flax
#

x && actualspread is a common-enough pattern to warrant that, i guess

halcyon templeBOT
#
2jt0#0

Preview:ts function abc(d: {d: string} | null) { const aux = { a: "t", b: 1, c: false, ...(null && {d: 11}), } // if d is null this expression ...(d && ..) does not compile, so why doesn't the typechecker complain here? aux }

sterile flax
#

value || {} errors
value && {} does not error
value ? {} : true errors
value ? {} : false does not error

grim edge
#

Ah, it really is a falsy expression exception, huh.

#

Since ...false is also an error

errant raven
halcyon templeBOT
#

@errant raven Here's a shortened URL of your playground link! You can remove the full link from your message.

2jt0#0

Preview:```ts
function test(value: null) {
return {...(value || {})}
}

function test1(value: null) {
value
return {...(null || {})}
}```

errant raven
#

so weird

#

or in other words, why doesn't the first example give the same error as the second? Why isn't typescript capable see that the param of a function will have a value on null always?

grim edge
#

I don't think the first examle should be an error?

#

Oh you're talking about Chris's examples

#

I think TS doesn't error on value && {} because it's useful and works at runtime, so why error?

errant raven
#
function test(value: null) {
  return {...(value || {})} // no error
}

function test1(value: null) {
  value
  return {...(null || {})} // error This kind of expression is always falsy.
}

this example

grim edge
#

The "this expression is always falsy" checks are brand new (TS 5.6) and intentionally cautious

errant raven
#

oh right

#

in older version it's the same