[英]Typescript type safety in conditional union type switch typing
我有一個簡單的函數,它采用聯合類型和boolean
作為參數,並且無法通過 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
而不引入像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;
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.