typescript - 条件联合类型开关类型中的打字稿类型安全
问题描述
我有一个简单的函数,它采用联合类型和 aboolean
作为参数,但无法让它由 Typescript 键入。
我有这个代码(游乐场在这里):
type A = 'a' | 'A';
function f(a: A, b: boolean): string {
if (b) {
switch (a) {
case 'a': return '';
case 'A': return '';
}
} else {
switch (a) {
case 'a': return '';
case 'A': return '';
}
}
}
编译器(strictNullChecks
何时启用)告诉我Function lacks ending return statement and return type does not include 'undefined'.
我真的不想添加default
案例,因为这里的目标是确保当我添加新类型时,A
我在f
. 而且我看不到我缺少哪个分支。
我可以通过编写来修复它(请参阅链接的游乐场):
function g(a: A): string {
switch (a) {
case 'a': return '';
case 'A': return '';
}
}
function f2(a: A, b: boolean): string {
if (b) {
return g(a);
} else {
return g(a);
}
}
(当然在现实生活中我需要两个不同的 g 函数,但对于打字问题这并不重要)。
如何在f
不引入中间函数的情况下让 typescript 编译g
?
解决方案
您可以添加default
案例来修复它,例如
function f(a: A, b: boolean): string {
if (b) {
switch (a) {
case 'a': return '';
case 'A':
default: return '';
}
} else {
switch (a) {
case 'a': return '';
case 'A':
default: return '';
}
}
}
您还可以通过返回类型来修复它,never
例如
function f(a: A, b: boolean): string {
if (b) {
switch (a) {
case 'a': return '';
case 'A': return '';
default:
const _exhaustiveCheck: never = a;
return _exhaustiveCheck;
}
} else {
switch (a) {
case 'a': return '';
case 'A': return '';
default:
const _exhaustiveCheck: never = a;
return _exhaustiveCheck;
}
}
}