我正在寻找一种很好的方法来断言为特定变量推断出的 TypeScript 类型。这是我现在正在使用的:
function assertType<T>(value: T) { /* no op */ }
assertType<SomeType>(someValue);
当我想确保涵盖函数返回的所有可能值时,这特别有用。例如:
function doSomething(): "ok" | "error" { ... }
const result = doSomething();
if(result === "error") { return; }
assertType<"ok">(result);
// do something only if result is OK
这确保向总和
"ok" | "error"
添加新的变体,如"timeout"
,将触发类型错误。
assertType
解决方案在实践中有效,但我发现调用 noop 很不幸,我希望可能有一种本地方法可以做到这一点,例如:
if(result === "error") { return; }
<"ok">result // magic
// do something only if result is OK