MCPcopy Create free account
hub / github.com/nodejs/node / narrowTypeBySwitchOnDiscriminant

Function narrowTypeBySwitchOnDiscriminant

test/fixtures/snapshot/typescript.js:71063–71103  ·  view source on GitHub ↗
(type, switchStatement, clauseStart, clauseEnd)

Source from the content-addressed store, hash-verified

71061 return everyClauseChecks ? getTypeWithFacts(type, 2097152 /* TypeFacts.NEUndefinedOrNull */) : type;
71062 }
71063 function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) {
71064 // We only narrow if all case expressions specify
71065 // values with unit types, except for the case where
71066 // `type` is unknown. In this instance we map object
71067 // types to the nonPrimitive type and narrow with that.
71068 var switchTypes = getSwitchClauseTypes(switchStatement);
71069 if (!switchTypes.length) {
71070 return type;
71071 }
71072 var clauseTypes = switchTypes.slice(clauseStart, clauseEnd);
71073 var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, neverType);
71074 if ((type.flags & 2 /* TypeFlags.Unknown */) && !hasDefaultClause) {
71075 var groundClauseTypes = void 0;
71076 for (var i = 0; i < clauseTypes.length; i += 1) {
71077 var t = clauseTypes[i];
71078 if (t.flags & (131068 /* TypeFlags.Primitive */ | 67108864 /* TypeFlags.NonPrimitive */)) {
71079 if (groundClauseTypes !== undefined) {
71080 groundClauseTypes.push(t);
71081 }
71082 }
71083 else if (t.flags & 524288 /* TypeFlags.Object */) {
71084 if (groundClauseTypes === undefined) {
71085 groundClauseTypes = clauseTypes.slice(0, i);
71086 }
71087 groundClauseTypes.push(nonPrimitiveType);
71088 }
71089 else {
71090 return type;
71091 }
71092 }
71093 return getUnionType(groundClauseTypes === undefined ? clauseTypes : groundClauseTypes);
71094 }
71095 var discriminantType = getUnionType(clauseTypes);
71096 var caseType = discriminantType.flags & 131072 /* TypeFlags.Never */ ? neverType :
71097 replacePrimitivesWithLiterals(filterType(type, function (t) { return areTypesComparable(discriminantType, t); }), discriminantType);
71098 if (!hasDefaultClause) {
71099 return caseType;
71100 }
71101 var defaultType = filterType(type, function (t) { return !(isUnitLikeType(t) && ts.contains(switchTypes, getRegularTypeOfLiteralType(extractUnitType(t)))); });
71102 return caseType.flags & 131072 /* TypeFlags.Never */ ? defaultType : getUnionType([caseType, defaultType]);
71103 }
71104 function getImpliedTypeFromTypeofGuard(type, text) {
71105 switch (text) {
71106 case "function":

Callers 2

getTypeAtSwitchClauseFunction · 0.85

Calls 11

getSwitchClauseTypesFunction · 0.85
getUnionTypeFunction · 0.85
filterTypeFunction · 0.85
areTypesComparableFunction · 0.85
isUnitLikeTypeFunction · 0.85
extractUnitTypeFunction · 0.85
sliceMethod · 0.65
containsMethod · 0.45
pushMethod · 0.45

Tested by

no test coverage detected