Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use assertion in destructuring syntax?

Tags:

typescript

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.

like image 855
Zheeeng Avatar asked Mar 15 '26 22:03

Zheeeng


1 Answers

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.

like image 82
wrager Avatar answered Mar 19 '26 00:03

wrager



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!