#Default destructured value issue
22 messages · Page 1 of 1 (latest)
{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
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
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
Yeah, it would probably be weirder if it ignored it.
even tho i know that it will never be a number, typescript doesnt know that
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.
i am sorry, but have you also answered to this in your reply?
is this okay?
Sure
It'd be weirder if you did = 123 and it didn't include number afterwards, I think.
yea it would
but lets go back to, how could there ever be 123 if the type is string, not string|undefined
the reason is because that's sometimes useful for writing TS code that might be called by JS consumers.
hmm, okay, nevermind i guess.
The idea is you can write code that's defensive against null and undefined values without explicitly accepting null or undefined values.