I just practicing Typescript with React. When I come to this code, I found that either ! 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 to tell Typescript that this never has null nor undefined value. And ?. optional chaining is to prevent error when no property found and return undefined. In the above case, I can use ! or ?. or even both of them combined !?., and Typescript compiler not protesting. So which one is best and safest to use?