score:1
assuming you have defined user as:
const user: user|undefined = ...;
if you want to access a property of user, use this syntax:
user!.firstname
this tells typescript that you know what you're doing and that user
is never undefined or null. it also tells typescript that properties accessed this way are not to be assumed to possibly be null
or undefined
, which i'm guessing is why you were now getting more errors.
note!
const user: user|undefined = ...;
is redundant typing. you can just revert back to using
const user: user = ...;
but instead of using the ?.
operator to access properties, continue using !.
.
sorry if this is your first time using typescript. it's usually not this bad.
score:1
consider splitting your components into:
- components that must have a user
- components that may have a user
from the component that may have a user, render the component that must have one.
class usercomponent extends react.component<{ user: user }> {
render() {
// note: since user must be defined for this component, we are able to access properties without the ? or ! syntax
return (
<div>{this.props.user.firstname}</div>
)
}
}
// note: this.state.user is optional, and therefore is initialized as undefined
class mayhaveusercomponent extends react.component<{}, { user?: user }> {
render() {
if (this.state.user) {
return <usercomponent user={this.state.user} />
}
return (
<div>no user yet!</div>
)
}
setuser(user: user) {
this.setstate({ user: { ...user, ...this.state.user } })
}
}
score:1
you're not just making typescript happy here. if you pass user: undefined
to code that expects there to be a user object, then that will definitely cause runtime errors when you use undefined
like an object. these checks are necessary if that is to be allowed.
typically, i handle that in react by returning a render early if a required value is null
or undefined
. after that return, you can assume the user exists as normal.
class component({ user: user | null | undefined }) {
if (!user) return <someloadingindicator /> // or: return null, or whatever
// from here on, `user` is known to be of type `user`, not null, and not undefined.
return <div>{user.lastname}</div>
}
adding conditions, such as
if(user)
does not seem to satisfy ts.
it really does though. you just have to be on a conditional branch where the check has been run. meaning you have to be in the { }
of an if statement:
const user: user | null = math.random() > 0.5 ? getuser() : null
if (user) {
// here user is of type: user
} else {
// here user is of type: null
}
// here user is of type: user | null
or in code that could only run if the conditional was truthy.
const user: user | null = math.random() > 0.5 ? getuser() : null
if (!user) {
// here user is of type: null
throw new error("user is required!")
}
// here user is of type: user
Source: stackoverflow.com
Related Query
- TypeScript undefined object type messes things up
- React / Typescript : pushing obj into array of object and undefined type
- What TypeScript type should I use to reference the match object in my props?
- Ref object is possibly undefined TypeScript React
- Typescript how to type custom key in an object
- TypeScript type for value of key in object
- Typescript - infer generic type from object prop value
- TypeScript | Can't loop over a custom type Object
- Mapping data object with a type field to specific React Components with TypeScript
- Apollo Cache - Missing selection set for object of type undefined returned for query field names
- Object or Boolean how to declare type in Typescript
- React typescript - object is possibly undefined
- Don't understand TypeScript function signature with weird object type as param
- Autocomplete in return type Typescript based on input object
- Typescript generic type for nested object properties
- Typescript object possibly undefined when looking for objects inside an array
- How to correctly type a null value in typescript react app, retrieved from an JSON object (api call) when using Object.entries to retrieve the value?
- object parameters type definition in typescript
- Object is of type unknown error when using Typescript with React
- Typescript dynamically infer type from object
- TypeScript + React: How do I type a `rest` props that collects the rest of the props into an object and later spread them to some element?
- Typescript extract type of nested object in template type
- Object is possibly undefined react typescript in the dropdown component
- Type Error: Cannot convert undefined or null to object
- NextJS Typescript - Object is possibly undefined after guard?
- Typescript map array of objects giving error: property '(property)' does not exist on type object
- How do I provide default values to optional nested props of type Object in typescript + React?
- React.JS Typescript - OnChange says "A component is changing a controlled input of type text to be uncontrolled in OnChange" for State Object
- Redux combineReducers Uncaught Type error: Cannot convert undefined or null to object
- Proxied Object Assignment Type Error TypeScript
More Query from same tag
- How to return objects that have matching value when comparing to a separate array
- horizontally scroll a table with mouse wheel in react without DOM Selector?
- Can not render component correctly in ReactJS
- How to clear input fields after submit in react
- Rendering local images/javascript snippets in reactjs
- Using external script (in JavaScript) in Gatsby JS
- Updating 'state' dynamically in React overwrites entire state
- Setting state in React.js (TypeScript) is giving problem
- Table row gets deleted but value remains
- componentDidMount() returns an undefined value
- Pagination Item returns undefined after a few clicks
- react: This expression is not callable. Type 'never' has no call signatures
- Do closures work the same way on class methods?
- Delete an element from an array (RecoilJS)
- React - Sort by newst date in useState
- Decorators problem: experimental syntax 'decorators-legacy' isn't currently enabled
- parse data from firebase in react render
- How can i display the quantity of the items in my shopping cart on every pages of my react/nextjs application
- react hoc for checkbox and radio component
- Having Object value but react says undefined react redux
- Notify child components of transition state in TransitionGroup
- Converting Array.map + Promise.all to Observable
- Multiple condition in one function
- How do I pass props from a child class to parent then to a (different) child class?
- How to change the background of a styled.div if the window is scrolled to the top?
- How to render different message based on current url / url fragment
- How to close a modal window clicking outside in React + Redux app?
- 304 Error using Netlify Functions in create-react-app
- On state change of one component re-render second component
- material UI grid layout design