我的逻辑工作方式不同,我打算或编译器不理解我想做什么?
Line i4:This condition will always return true since the types SubjectType.Both | SubjectType.A and SubjectType.B have no overlap.
j1 enum SubjectType {
j2 BOTH,
j3 A,
j4 B,
j5 }
i1 switch ( subjectType: SubjectType ) {
i2 case SubjectType.BOTH
i3 case SubjectType.A:
i4 if( subjectType !== SubjectType.B ) {
i5 //Do thing A
i6 }
i7 case SubjectType.B:
i8 if( subjectType !== SubjectType.A ) {
i9 //Do thing B
i10 }
i11
i12 break;
i13 default:
i14 throw new TypeError( `Unknown SubjectType ${subjectType} provided` );
i15 }
编辑:事实上,我的逻辑是错误的。
i1 switch ( subjectType: SubjectType ) {
i2 case SubjectType.BOTH
i3 case SubjectType.A:
i4 //Do thing A, if type A | BOTH
i5
i6 case SubjectType.B:
i7 if( subjectType !== SubjectType.A ) {
i8 //Do thing B
i9 }
i10
i11 break;
i12 default:
i13 throw new TypeError( `Unknown SubjectType ${subjectType} provided` );
i14 }
subjectType
变量/const只能有三种状态:A
,B
和BOTH
。考虑这个例子:
enum SubjectType {
BOTH,
A,
B,
}
const subjectType: SubjectType = null as any
function foo() {
switch (subjectType) {
case SubjectType.BOTH:
case SubjectType.A:
if (subjectType !== SubjectType.B) {
//Do thing A
}
case SubjectType.B:
if (subjectType !== SubjectType.A) {
//Do thing B
}
break;
default:
throw new TypeError(`Unknown SubjectType ${subjectType} provided`);
}
}
switch
中的这两行:
case SubjectType.BOTH:
case SubjectType.A:
表示subjectType
是BOTH
或A
中的一个,而不是B
。
然后,你试图比较subjectType
和B
if (subjectType !== SubjectType.B) {
,但TS和我都清楚,在这种情况下,subjectType
不能是B
。