tsc 4.9+ · Build and types
The message
error TS18048: 'user' is possibly 'undefined'.
What it means
The value may be undefined and you have not handled that possibility; this is tsc catching a future Cannot read properties of undefined for you. It shows up on optional fields, on the result of an array find(), and on environment variables that might not be set. Deciding what happens when it is missing is the fix: cut early with if (!user) return null, or short-circuit with user?.name. Silencing it as user!.name is a declaration that you guarantee it — and when the guarantee is wrong it comes back as a runtime exception, with none of the safety a check would have left behind.
The fix
There is no one-line command for this. The explanation says what to look at instead.
- Printed by
- tsc 4.9+
- Build and types
- 10
Build errors are a tool refusing before anything runs, so they break nothing at the moment they appear — but they do ask two questions: will you fix the type or the path to match the real shape, or will you push that one line through with an as any or a suppression comment — and it is here that the things which are only true on your own machine, letter case, extensions and environment variables, show themselves for the first time.
Reading an error message
- Read from the first line down. The lower you go the more it is about the tool’s internals; the cause is usually at the top.
- If there is a file and a line number, start there — not the top stack frame, but the topmost line that names a file you wrote.
- Search the message verbatim, but strip your own paths and variable names first; those are what stop the search from matching.
- The same condition is worded differently across tool versions. If results look wrong, add the version number to the query.
- Before pasting a fix, check what it throws away. Some of these cannot be undone.
Common questions
Q. What does “error TS18048: 'user' is possibly 'undefined'.” mean?
The value may be undefined and you have not handled that possibility; this is tsc catching a future Cannot read properties of undefined for you. It shows up on optional fields, on the result of an array find(), and on environment variables that might not be set. Deciding what happens when it is missing is the fix: cut early with if (!user) return null, or short-circuit with user?.name. Silencing it as user!.name is a declaration that you guarantee it — and when the guarantee is wrong it comes back as a runtime exception, with none of the safety a check would have left behind.
Q. How do I fix it?
There is no one-line command. The explanation above says what to look at instead.
Q. Which tool prints this?
tsc 4.9+. It sits under Build and types, and the message runs to 6 words.