TypeScript:如何无误地访问 onChange 事件数据? (对象可能是 'null')

TypeScript: How to access onChange event data without error? (Object is possibly 'null')

请参阅下面的最小示例:

/** @jsx h */
import { h, FunctionalComponent } from 'preact';

const Test: FunctionalComponent = () => {
  return (
    <select
      value="1"
      onChange={(event) => {
        console.log(event.target.value);
      }}
    >
      <option value="1">1</option>
      <option value="2">2</option>
    </select>
  );
};

如何解决显示 Object is possibly 'null' 的错误?

这是一个 "TypeScript safety check" 通知您 event.target 可能为空,这将导致访问 event.target.value 在 run-time.[=16 处抛出错误=]

这个 warning/error 可以使用 "non-null assertion operation":

静音
<select value="1" onChange={(event) => {
    /* Add ! after target to state that "event.target!" is defined and 
       that value field can be safely accessed. This is a non-null 
       assertion */
    console.log(event.target!.value);
}}>

或者在访问之前检查 event.target 是否已定义:

<select value="1" onChange={(event) => {

    const { target } = event;
    if(target) {
        /* The ! is not needed seeing target is dedeuced as being defined */
        console.log(target.value);
    }
}}>

确保在访问之前检查 event.target.value。见下文

    <select value="1" onChange={(event) => {
    event.target.value? console.log(event.target.value):null;
}}

我在选择文件时遇到了类似的问题

<input
  type="file"
  onChange={(event: React.ChangeEvent<HTMLInputElement>): void => {
    formik.setFieldValue(
      "file",
      (event?.target.files && event?.target?.files[0]) ?? ""
    );
    formik.setFieldValue(
      "fileName",
      (event?.target.files && event?.target?.files[0].name) ?? ""
    );
  }}
/>;