-1

I m working with React-Router-v6 and i want to pass some props as location in useRoutes(). I m a little bit confused because i find an example Modal although this example doesn't use useRoutes() i was trying to run it but some operators throws some errors when i run it.
I find the ?: as conditional operator precedence but i cannot find how it works. It looks like something as ... ? ... : ... but this doesn't work for me.

My whole question is how the command below works and what the following operators (as and ?:) do.

let state = useLocation().state as { backgroundLocation?: Location };

PS: I think that the whole command is something like assign the Location as new property of state with name backgroundLocation but i still don't comprehend the whole functionality.

szZzr
  • 33
  • 7
  • `?:` isn't an operator in what you've posted, that's **TypeScript**. The errors are presumably because you're treating it like it's JavaScript. – jonrsharpe Jan 07 '22 at 15:51
  • If you notice at this [link](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#operator_precedence) `?:` refers as an operator. Thks. – szZzr Jan 07 '22 at 15:55
  • 3
    Right, but that's for JavaScript and, again, _you have TypeScript_. Everything from `as` onwards is **not** JavaScript, and would be erased in compilation. Note that what you've linked to is a `.tsx` file. – jonrsharpe Jan 07 '22 at 15:56
  • Possible dupe: https://stackoverflow.com/q/55781559/3001761 – jonrsharpe Jan 07 '22 at 15:57
  • @jonrsharpe you 're right. Thank you! – szZzr Jan 07 '22 at 16:03

1 Answers1

1

This is a TypeScript type assertion. It's unrelated to the conditional operator.

as tells TypeScript "ignore what you compute the type to be, and instead assume it's the type I tell you". { backgroundLocation?: Location } means an object with an optional property backgroundLocation. The value of backgroundLocation is either undefined (thanks to being optional) or a Location.

If your project is not set up to transpile typescript, then you'll need to remove the typescript and just do plain javascript. To do so for this code, simply delete as { backgroundLocation?: Location }

Nicholas Tower
  • 72,740
  • 7
  • 86
  • 98
  • as tells TypeScript "ignore what you compute the type to be, and instead assume it's the type I tell you" -> that's not entirely true. This line wouldn't work: const test = "hello" as boolean because neither type overlaps with the other. – jperl Jan 07 '22 at 16:04
  • @jperl it's true that typescript will metaphorically ask "are you sure?" if you make a really egregious assertion, to which you can respond "yes, i'm sure" via `as unknown as boolean`. – Nicholas Tower Jan 07 '22 at 18:09