#LocalPlayer type hinting in localScript

1 messages · Page 1 of 1 (latest)

quaint sedge
#

So I am using --!strict in all of my scripts because I want to have type hinting in my scripts.

Today I opened a localScript and tried accessing game.Players.LocalPlayer.<something>
and I got the errorType Error: Value of type 'Player?' could be nil.
Now I am aware that this can happen on a serverScript, but why do I get this error on localScripts? LocalPlayer should never be nil in this case

Is there an elegant way to deal with this in localScripts? Right now I am checking every time if the LocalPlayer is nil and otherwise throwing an error (which again, should never happen), but this seems really annoying to do every time.

Thank you!

quaint oasis
#

I'm pretty sure this could be caused cuz of core scripts running before local scripts and local player can be nil for them so that's why its player? and not player

#

Not 100% sure tho

foggy trout
#

you should state the type of the variable you are storing player in, or cast type player to it:

local Player: Player = game.Players.LocalPlayer

Or

local Player = game.Players.LocalPlayer :: Player

I’m 100 percent sure the first one will work, not sure about the second one with casting

#

if you need you could cast and define the type

quaint sedge
#

Heyy,
so the first one actually did not work, but the casting worked perfectly! Thank you very much!
(if you are wondering why the first one didn't work, this is the error message - Type Error: Type 'Player?' could not be converted into 'Player'; this is because the 1st component of the union is nil, which is not a subtype of Player`

tired sigil
#

just a word of advice if you're struggling to refine an optional type you probably aren't ready for typestrict. just use --!nonstrict and reserve annotations only for places you care about e.g function parameters and some obvious variables like character.humanoid, just cast whereever you want the hints

quaint sedge
#

I see, thank you very much!
Do people usually use --!strict in general? or as it not as common

tired sigil