In Typescript, how can I use assertion in destructuring?
type StringOrNumber = string | number
const obj = {
foo: 123 as StringOrNumber
}
const { foo } = obj
I didn't find a convenient way to add number type assertion on const foo. Two workarounds are:
// A:
const { foo } = obj as { foo: number }
// B:
const { foo: foo2 } = obj
const foo = <number>foo2
The first is a burden to rewrite the obj's type when its type is nested and complicated. The second seems weird. I'm assuming such a syntax like:
const { <number>foo } = obj
can absolutely help us asserting the type from nested and complicated destructuring.
According to the documentation, there is no way for casting the type right when destructuring. Apparently, there are no workarounds other than those that you provided.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With