• python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Facebook Twitter Instagram
Devs Fixed
  • python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Devs Fixed
Home ยป Resolved: How to read the value of a Record in typescript (the right way)

Resolved: How to read the value of a Record in typescript (the right way)

0
By Isaac Tonny on 16/06/2022 Issue
Share
Facebook Twitter LinkedIn

Question:

I have the following two types
Now I have a some items:
and I try to read the the value of version in value object
but I’m getting the error:
In the console I can actually see that the value desc is printed out but I get this error in vs code. I could avoid this error by casting the SortOption object to any
but this looks like a dirty hack and I would like to know how I can solve this in a proper way.

Answer:

You’ve defined SortOption as this type:
That means that item.value might be a string or it might be a Record<string, 'desc' | 'asc'>.
For instance, this is also a valid Item:
And if you want to treat the value like a Record you have to prove it is one first at runtime in order to narrow down the type.
For example:
See playground

If you have better answer, please add a comment about this, thank you!

typescript
Share. Facebook Twitter LinkedIn

Related Posts

Resolved: When converting markdown to latex with pandoc, how can I end a block before the next heading?

26/03/2023

Resolved: TYPO3 SQL error: Field ‘tx_imagezoom_set’ doesn’t have a default value

26/03/2023

Resolved: std::regex_replace to replace multiple combinations

26/03/2023

Leave A Reply

© 2023 DEVSFIX.COM

Type above and press Enter to search. Press Esc to cancel.