How can I implement type assertion in destructuring with Typescript?
type StringOrNumber = string | number
const obj = {
foo: 123 as StringOrNumber
}
const { foo } = obj
I've been struggling to find a simple way to apply the number
type assertion on const foo
. Two possible solutions are:
// A:
const { foo } = obj as { foo: number }
// B:
const { foo: foo2 } = obj
const foo = <number>foo2
The first option requires redefining the type of obj
when it's complex and nested. The second approach feels unconventional. It would be great if we could use syntax like:
const { <number>foo } = obj
This kind of syntax would make asserting types during nested and complicated destructuring much easier.