score:4
optional chaining ?.
is safer to use than non-null assertions !
.
consider the following interface:
interface foo {
bar?: {
baz: string;
}
}
the bar
property is optional. if it doesn't exist it will be undefined
when you read it. if it does exist it will have a baz
property of type string
. if you just try to access the baz
property without making sure that bar
is defined, you'll get a compiler error warning you about a possible runtime error:
function oops(foo: foo) {
console.log(foo.bar.baz.touppercase()); // compiler error
// -------> ~~~~~~~
// object is possibly undefined
}
optional chaining has actual effects at runtime and short-circuits to an undefined
value if the property you're trying to access does not exist. if you don't know for sure that a property exists, optional chaining can protect you from some runtime errors. the typescript compiler does not complain with the following code because it knows that what you are doing is now safe:
function optchain(foo: foo) {
console.log(foo.bar?.baz.touppercase());
}
optchain({ bar: { baz: "hello" } }); // hello
optchain({}); // undefined
you should use optional chaining if you are not sure that your property accesses are safe and you want runtime checks to protect you.
on the other hand, non-null assertions have no effect whatsoever at runtime. it's a way for you to tell the compiler that even though it cannot verify that a property exists, you are asserting that it is safe to do it. this also has the effect of stopping the compiler from complaining, but you have now taken over the job of ensuring type safety. if, at runtime, the value you asserted as defined is actually undefined, then you have lied to the compiler and you might hit a runtime error:
function nonnullassert(foo: foo) {
console.log(foo.bar!.baz.touppercase());
}
nonnullassert({ bar: { baz: "hello" } }); // hello
nonnullassert({}); // 💥 typeerror: foo.bar is undefined
you should only use non-null assertions if you are sure that your property accesses are safe, and you want the convenience of skipping runtime checks.
score:2
those are completely different things.
the null assertion operator !.
is you, the programmer, asserting to the compiler that you know for a fact that the property access cannot fail for reasons the compiler cannot prove. it is no more safe from a runtime error than any other assertion that you the programmer make to the compiler that you know better that it does.
const foo = null;
foo!.someproperty; // compiles but you will get a typeerror! cannot read property 'someproperty' of null or undefined.
the other is the optional chaining operator. it is basically shorthand for this common javascript pattern:
const something = foo && foo.bar && foo.bar.baz;
but it's better than just shorthand, because the above will fail if one of those values is falsey but some falsey values support property access. with null coalescing you just write:
const something = foo?.bar?.baz;
and you're done. and just like the javascript version it's "safe" in that it's guaranteed not to result in a runtime error from trying to access a property of a null reference.
in the particular case you have there, you probably want something like this:
const enteredtext = textinputref.current?.value || '';
where it's very clear that the result is a string no matter what.
Source: stackoverflow.com
Related Query
- Typescript optional chaining combined with ternary operator parsing error
- How should I go about method chaining in TypeScript (like how Tiptap does it)
- How to add TypeScript 3.7 Optional Chaining support to create react app project
- Default property value in React component using TypeScript
- When should I be using React.cloneElement vs this.props.children?
- What is the difference between .ts and .tsx extensions. Both are used as extensions for typescript files in react. So where should we use them?
- Should you ever use this.setState() when using redux?
- What TypeScript type should I use to reference the match object in my props?
- typesafe select onChange event using reactjs and typescript
- Typescript complains Property does not exist on type 'JSX.IntrinsicElements' when using React.createClass?
- How do I restrict the type of React Children in TypeScript, using the newly added support in TypeScript 2.3?
- Using a forwardRef component with children in TypeScript
- Using state in react with TypeScript
- React - using TypeScript vs Flow vs?
- Using styled-components with props and TypeScript
- I am using Redux. Should I manage controlled input state in the Redux store or use setState at the component level?
- How to rewrite the protected/private route using TypeScript and React-Router 4, 5 or 6?
- You should not use Route or withRouter() outside a Router when using react-router 4 and styled-component in react
- React with Typescript -- Generics while using React.forwardRef
- Type of Axios mock using jest typescript
- Using document.querySelector in React? Should I use refs instead? How?
- What TypeScript type should NextJS _app.tsx Component and pageProps be?
- Destructuring props in the function parameters using TypeScript
- Using React.lazy with TypeScript
- Typescript errors when using jest mocks
- Using React forwardRef with Typescript generic JSX arguments
- How to import shared typescript code using create-react-app (no eject)?
- Using typescript in react,stateless component not assignable to type 'React.SFC'
- Using dot notation with functional component in TypeScript
- Typescript React: Conditionally optional props based on the type of another prop
More Query from same tag
- JavaScript not working when getting content through api
- Creating a line with an arrow in React
- Failed prop type: The prop justify of Grid must be used on container
- React hook - HowTo pass state to child components
- ESLint Error 'Invalid count value' when run with --fix
- Jest function fails to fire after network request in react component
- react TextField material UI value
- Using React.js to display a different CTA button on the site's footer, depending on the page path
- how to add and set a font in JsPDF?
- React/Redux Component will not render
- Too many re-renders in React
- TypeError: (intermediate value)(intermediate value)(intermediate value) is not iterable
- React router dom params issue
- Next js: next auth provider + redux provider
- How to group messages in a chat instead of having each new message in a new section?
- How should I parse this json object in react with lifecycle method?
- React hooks array specific problem with structure
- Using 'useEffect' inside my App function in my _app.js for my NextJS app
- React customize Material-UI Icons styles
- Function passing null at first run
- Cloud Firestore Query with React - First Character Is Numeric
- I want an error message if the entered username is not present on github
- Not able to access the animate.css's animation keyframe names from scss file
- change div background color on click REACT
- Gatsby - how to fix "eliminate render-blocking resources" (google fonts)
- Extracting one value from array into a variable - ReactJS
- How to lock the position of close button with paper component of modal in material ui for responsive screen?
- Flow type for useMemo hook
- calculation and changing state inside setstate in reactjs
- React-select creatable - only allow one created option