实现说明
函数 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);