TypeScript中是否有类似Kotlin的requireNotNull空安全替代方案?
TypeScript中替代Kotlin requireNotNull的空安全方案
如果你需要类似Kotlin requireNotNull 的空安全检查(即值为null时抛出错误,同时让TypeScript确认值非空),可以参考以下几种方案:
1. 自定义requireNotNull函数
这是最贴近Kotlin原生方法的方案,自己实现一个断言函数,运行时检查值是否为null/undefined,不符合则抛出错误,TypeScript会自动推断返回值为非空类型:
function requireNotNull<T>(value: T | null | undefined, errorMessage?: string): T { if (value == null) { throw new Error(errorMessage ?? "Value must not be null or undefined"); } return value; } // 使用示例 const userId = requireNotNull(getUserId(), "UserId cannot be null"); // 此时userId的类型被推断为string
2. 非空断言操作符!!(你当前的用法)
TypeScript中的!!就是非空断言操作符,和Kotlin的!!作用完全一致——告诉TypeScript编译器“这个值一定不是null或undefined”,但运行时如果值确实为null,会直接抛出TypeError。用法如下:
const userId = getUserId()!!;
注意:仅当你能100%确定运行时值不会为null时使用,否则会导致运行时错误。
3. 显式条件检查(类型守卫)
通过if语句显式检查值是否为null,TypeScript会自动缩小变量的类型范围,同时你可以自定义错误处理逻辑:
const userId = getUserId(); if (userId == null) { throw new Error("UserId is required"); // 也可以在这里做其他处理,比如返回、跳转页面等 } // 此时userId的类型已被缩小为string
4. 空合并操作符??(兜底默认值场景)
如果不需要抛出错误,而是希望给一个默认值,可以用空合并操作符??,类似Kotlin的?:操作符:
const userId = getUserId() ?? "default-user-id"; // 此时userId的类型为string(原类型或默认值类型的联合)
内容的提问来源于stack exchange,提问作者STEEL
相关产品推荐
相关产品推荐

