#Default destructured value issue

22 messages · Page 1 of 1 (latest)

fair scaffold
#

Look at the following code:

const BAR_SCHEMA = z.object({
  foo: z.string(),
});

const {foo = 123} = BAR_SCHEMA.parse("whatever");

console.log(foo);

am i doing something wrong or should typescript warn me that foo will never be 123, cause Zod already parsed it and it will never be undefined

#
{foo = 123}
{foo = "foobar"}
{foo = true}

this will never happen, the default parameter is redundant, and idk but i feel like TS should warn me about this

#

Oh, it doesnt seem like a Zod issue..

const options = {
  foo: "hello",
}

const {foo = 123} = options;

console.log(foo);
#

Default destructured value issue

iron forum
#

It wouldn't make your code any safer to disallow destructuring defaults even when object properties are guaranteed to not be undefined; TypeScript's goal is to encourage safer code, but not really to discourage unnecessary code

fair scaffold
#

i know that foo will never be undefined, and if i wrote {foo = "bar"}, i would be ok with that, its string anyways

#

but writing {foo = 123} actually modifies the type

#

to number|string

surreal schooner
#

Yeah, it would probably be weirder if it ignored it.

fair scaffold
#

even tho i know that it will never be a number, typescript doesnt know that

surreal schooner
#

TS sometimes allows you to check for undefined/null values even if the type says they won't be there - part of the reason is because that's sometimes useful for writing TS code that might be called by JS consumers.

#
function foo(x: string) {
    if(x === 0) {} // error
    if(x === undefined) {} // no error
}
#

Basically, if you want to add a default value "Just In Case", you can do that.

fair scaffold
#

is this okay?

surreal schooner
#

Sure

#

It'd be weirder if you did = 123 and it didn't include number afterwards, I think.

fair scaffold
#

but lets go back to, how could there ever be 123 if the type is string, not string|undefined

surreal schooner
#

the reason is because that's sometimes useful for writing TS code that might be called by JS consumers.

fair scaffold
#

hmm, okay, nevermind i guess.

surreal schooner
#

The idea is you can write code that's defensive against null and undefined values without explicitly accepting null or undefined values.