如何开启 strictNullChecks 并处理可选链与空值合并

解读

国内一线团队(阿里、字节、美团等)的 React 项目普遍基于 TypeScript + Vite / Webpack 工程化模板。面试官问“如何开启 strictNullChecks 并处理可选链与空值合并”,表面考察 tsconfig 配置,实则验证三点:

  1. 你是否真的在工程里关过“any 地狱”,敢不敢把 null 检查开到最严;
  2. 面对后端接口、埋点、第三方 SDK 等不可靠数据,能否用 TS 原生能力把运行时崩溃消灭在编译期;
  3. 能否在 React 组件、自定义 Hook、工具函数三个维度给出一致且可复制的空值治理套路。
    答“在 tsconfig 里把 strictNullChecks 设成 true”只能拿 30 分,必须结合 React 实际场景(useState 初始值、接口返回值、事件回调、Ref 解包)给出“编译期 + 运行时”双保险方案。

知识点

  1. strictNullChecks 与 strict 的关系
    • strict=true 会一次性打开 strictNullChecks、strictFunctionTypes 等 6 项子规则,国内项目推荐直接 strict=true,再针对性关闭个别规则。
  2. 可选链(?.)与空值合并(??)的 TC39 阶段与降级策略
    • 语法已 Stage 4,@babel/preset-typescript / esbuild / swc 均默认支持;如要兼容 IE11,需 @babel/plugin-proposal-optional-chaining + @babel/plugin-proposal-nullish-coalescing。
  3. React 特有坑位
    • useRef<T>(null) 的 .current 在首次渲染时为 null,必须加“非空断言”或“类型谓词”收窄;
    • 表单受控组件 value={xxx ?? ''},避免把 null 丢给 DOM 产生 warning;
    • 服务端渲染(Next.js)下,initialProps 可能为 undefined,需在 getServerSideProps 里用 ?? 给默认值。
  4. 编译期“绝对安全”三件套
    • 非空断言 !:只在 100% 确定时用,代码评审需注释理由;
    • 类型谓词(isXXX):把 unknown 或 any 收窄成可靠类型;
    • 断言签名(asserts x is T):封装校验函数,失败直接抛错,逻辑后续无需再判空。
  5. 运行时兜底策略
    • 对后端接口使用 zod / yup / joi 做 schema 校验,把 null 转 0、''、[] 等业务默认值;
    • 对关键链路(支付、下单)使用 Sentry 上报 “Cannot read properties of null” 错误,监控补漏。

答案

  1. 开启 strictNullChecks
    新建或修改 tsconfig.json:

    {
      "compilerOptions": {
        "strict": true,          // 一步到位打开 strictNullChecks
        "esModuleInterop": true,
        "jsx": "react-jsx"
      }
    }
    

    如果老项目无法一次性 strict,可只开 strictNullChecks:

    "strictNullChecks": true,
    
  2. React 组件内处理空值

    interface User {
      id: number;
      name: string;
      avatar?: string | null;
    }
    
    const Avatar: React.FC<{ user: User | null }> = ({ user }) => {
      // 1. 可选链 + 空值合并,保证 src 一定是 string
      const src = user?.avatar ?? '/default.png';
    
      // 2. 提前 return,避免后续逻辑出现 null
      if (!user) return <Skeleton />;
    
      return <img src={src} alt={user.name} />;
    };
    
  3. 自定义 Hook 里收窄类型

    function useUser(id: number | undefined) {
      const [user, setUser] = useState<User | null>(null);
    
      useEffect(() => {
        if (!id) return;          // 类型守卫,id 收窄成 number
        fetchUser(id).then(setUser);
      }, [id]);
    
      // 暴露“非空”版本给组件,减少重复判空
      return user as User | null;
    }
    
  4. 工具函数:断言签名

    function assertIsUser(value: unknown): asserts value is User {
      if (!value || typeof (value as any).id !== 'number') {
        throw new Error('Invalid user data');
      }
    }
    
  5. 兼容性处理(需支持 IE11)
    安装 babel 插件:

    pnpm add -D @babel/plugin-proposal-optional-chaining \
                @babel/plugin-proposal-nullish-coalescing
    

    在 babel.config.js 添加:

    module.exports = {
      presets: ['@babel/preset-react', '@babel/preset-typescript'],
      plugins: [
        '@babel/plugin-proposal-optional-chaining',
        '@babel/plugin-proposal-nullish-coalescing'
      ]
    };
    

拓展思考

  1. 空值治理与性能的平衡
    过度使用 ?? 会在热路径产生额外分支,对列表滚动、canvas 绘制等 60 fps 场景可用“Map 预填充”或“Sentinel 对象”把默认值提前算好,减少运行时判断。
  2. 与 React 18 concurrent 的冲突点
    useDeferredValue / startTransition 可能让组件“渲染到一半”被中断,若此时 Ref 解包未判空,仍会白屏。推荐把“可能为空的 Ref”做成 Hook:
    const useSafeRef = <T extends Element>() => {
      const ref = useRef<T>(null);
      const get = () => {
        if (!ref.current) throw new Error('Ref not ready');
        return ref.current;
      };
      return [ref, get] as const;
    };
    
  3. monorepo 场景
    如果业务包与组件库分属两个子仓库,组件库必须关闭 strictNullChecks 以保持兼容,可在业务仓库用 “skipLibCheck: false + composite: true” 强制子包重新生成 .d.ts,把 null 检查推到链路最前端,避免“库不 strict、业务 strict”导致的类型黑洞。