I'm learning TypeScript and React, and when I came across this code, I found that either !
(non-null assertion) and ?.
(optional chaining) can be used.
import { FC, FormEvent, useRef } from "react";
const NewTodo: FC = () => {
const textInputRef = useRef<HTMLInputElement>(null);
function todoSubmitHandler(ev: FormEvent) {
ev.preventDefault();
// v here v
const enteredText = textInputRef.current!?.value;
console.log(enteredText);
}
return (
<form onSubmit={todoSubmitHandler}>
<div>
<label htmlFor="todo-text">Todo Text</label>
<input type="text" id="todo-text" ref={textInputRef} />
</div>
<button type="submit">ADD TODO</button>
</form>
);
};
export default NewTodo;
What I know about !
is that it tells Typescript that this value is never null
nor undefined
. On the other hand, ?.
is used to prevent errors when no property found and instead returns undefined
. In the above example, I can use either !
or ?.
or even both of them combined !?.
, and Typescript compiler does not complain. So which one is best and safest to use?