← 中文资源

简体中文版本

NonNullable 剥离联合中的 null 与 undefined

用 NonNullable 把联合类型里的空值一侧剥掉:先取 find 的诚实返回类型,再让 mustFind 抛错后返回收紧的类型,两种形态类型都能对上。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

value: 3
misses stay honest: true
nullable side was: true narrowed side is: true

实现说明

函数 findSetting、mustFind是实现的聚合点。 Error 之前有一道守卫:坏状态在这里就停下,不会继续往下走。

使用要点

  • 守卫 found === undefined 命中后立刻用提前的 throw 结束这一轮。
  • 每一步打印都带着自己的标签:value:、misses stay honest:、nullable side was:。

常见问题

遇到格式错误的数据会怎样?

校验先行——Error 标记失败(位于 found === undefined),不会先做一半再失败。

不安装任何包也能运行吗?

可以,开箱即跑——没有引用任何内建 API 之外的东西。 文件在加载时定义 findSetting、mustFind。

入口签名:function findSetting(key: string)

核心语句

return settings.find((s) => s.key === key);
throw new Error(`missing setting: ${key}`);

代码示例

type Setting = { key: string; value: string };

const settings: Setting[] = [];

// The lookup may miss, so the honest return type includes undefined.
function findSetting(key: string): Setting | undefined {
  return settings.find((s) => s.key === key);
}

type Lookup = ReturnType<typeof findSetting>;
const isNullable: Lookup extends Setting | undefined ? true : never = true;

// NonNullable peels off null and undefined, keeping the rest of the union.
type Present<T> = NonNullable<T>;
type Narrowed = Present<Lookup>;
const isNarrowed: Narrowed extends Setting ? true : never = true;

// The classic use: assert-or-throw turns a nullable lookup into T.
function mustFind(key: string): NonNullable<Lookup> {
  const found = findSetting(key);
  if (found === undefined) {
    throw new Error(`missing setting: ${key}`);
  }
  return found;
}

settings.push({ key: 'retries', value: '3' });
const found = mustFind('retries');
console.log('value:', found.value);

const missing = findSetting('nope');
console.log('misses stay honest:', missing === undefined);
console.log('nullable side was:', isNullable, 'narrowed side is:', isNarrowed);