【发布时间】:2023-03-28 16:05:02
【问题描述】:
我有一个简单的函数,将联合类型和 boolean 作为参数,但无法让它由 Typescript 键入。
我有这个代码 (playground here):
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 函数,但对于打字问题这并不重要)。
如何让 typescript 编译 f 而不引入像 g 这样的中间函数?
【问题讨论】:
标签: typescript switch-statement union-types