Class UnionType
The UnionType implements a common JavaScript idiom in which the code is specifically
designed to work with multiple input types. Because JavaScript always knows the run-time type of
an object value, this is safer than a C union.
For instance, values of the union type (String,boolean) can be of type String
or of type boolean. The commutativity of the statement is captured by making
(String,boolean) and (boolean,String) equal.
The implementation of this class prevents the creation of nested unions.
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic final classImplements type unioning logic, sinceUnionTypes only actually need to perform unioning operations when being (re)built.Nested classes/interfaces inherited from class com.google.javascript.rhino.jstype.JSType
JSType.HasPropertyKind, JSType.Nullability, JSType.SubtypingMode, JSType.TypePair, JSType.WithSourceRef -
Field Summary
Fields inherited from class com.google.javascript.rhino.jstype.JSType
templateTypeMap -
Method Summary
Modifier and TypeMethodDescriptionautobox()Dereferences a type for property access.static UnionType.Builderbuilder(JSTypeRegistry registry) Creates aUnionType.Builderfor a newUnionType.booleanThis predicate is used to test whether a given type can be used as the 'function' in a function call.Gets the least supertype of this that's not a union.booleanAUnionTypecontains a given type (alternate) iff the member vector contains it.protected JSTypefindPropertyTypeWithoutConsideringTemplateTypes(String propertyName) Looks up a property on this type, but without properly replacing any templates in the result.com.google.common.collect.ImmutableList<JSType> Gets the alternate types of this union type.getLeastSupertype(JSType that) Gets the least supertype ofthisandthat.Computes the set of possible outcomes of theToBooleanpredicate for this type.getPropertyKind(String pname, boolean autobox) Checks whether the property is present on the object.getRestrictedTypeGivenOutcome(Outcome outcome) Computes the restricted type of this type knowing that theToBooleanpredicate has a specific value.getRestrictedUnion(JSType type) Returns a more restricted union type thanthisone, in which all subtypes oftypehave been removed.getTypesUnderEquality(JSType that) Computes the subset ofthisandthattypes if equality is observed.Computes the subset ofthisandthattypes if inequality is observed.Computes the subset ofthisandthattypes under shallow inequality.booleanbooleanisDict()Returns true iffthiscan be adict.booleanTests whether this type explicitly allows undefined (as opposed to ? or *).booleanThis predicate determines whether objects of this type can have thenullvalue, and therefore can appear in contexts wherenullis expected.booleanisObject()Tests whether this type is anObject, or any subtype thereof.booleanisStruct()Returns true iffthiscan be astruct.booleanbooleanTests whether this type is voidable.voidmatchConstraint(JSType constraint) Modify this type so that it matches the specified type.booleanThis predicate is used to test whether a given type can appear in a numeric context, such as an operand of a multiply operator.booleanThis predicate is used to test whether a given type can appear in anObjectcontext, such as the expression in awithstatement.booleanThis predicate is used to test whether a given type can appear in aStringcontext, such as an operand of a string concat (+) operator.booleanThis predicate is used to test whether a given type can appear in aSymbolcontextIf this is a union type, returns a union type that does not include the null type.If this is a union type, returns a union type that does not include the null or undefined type.If this is a union type, returns a union type that does not include the undefined type.testForEquality(JSType that) Comparesthisandthat.Downcasts this to a UnionType, or returns null if this is not a UnionType.<T> TVisit this type with the given visitor.Methods inherited from class com.google.javascript.rhino.jstype.JSType
areSimilar, assertFunctionType, assertObjectType, autoboxesTo, canCastTo, canTestForEqualityWith, canTestForShallowEqualityWith, containsReferenceAncestor, dereference, differsFrom, equals, findPropertyType, getDisplayName, getEnumeratedTypeOfEnumElement, getGreatestSubtype, getJSDocInfo, getPropertyKind, getTemplateParamCount, getTemplateTypeMap, getTypeParameters, getTypesUnderShallowEquality, getUnionMembers, hasAnyTemplateTypes, hasDisplayName, hashCode, hasProperty, isAllType, isArrayType, isBigIntObjectType, isBigIntOrNumber, isBigIntValueType, isBooleanObjectType, isBooleanValueType, isBoxableScalar, isCheckedUnknownType, isConstructor, isDateType, isEmptyType, isEnumElementType, isEnumType, isFunctionPrototypeType, isFunctionType, isGlobalThisType, isInstanceType, isInterface, isLiteralObject, isNamedType, isNativeObjectType, isNominalConstructorOrInterface, isNominalType, isNoObjectType, isNoResolvedType, isNoType, isNullType, isNumber, isNumberObjectType, isNumberValueType, isObjectType, isOnlyBigInt, isOrdinaryFunction, isRawTypeOfTemplatizedType, isReadonlyArrayType, isRecordType, isRegexpType, isResolved, isSomeUnknownType, isString, isStringObjectType, isStringValueType, isStructuralInterface, isStructuralType, isSubtype, isSubtype, isSubtypeOf, isSubtypeOf, isSubtypeWithoutStructuralTyping, isSuccessfullyResolved, isSymbol, isSymbolObjectType, isSymbolValueType, isTemplateType, isTemplatizedType, isUnionType, isUnsuccessfullyResolved, isVoidType, loosenTypecheckingDueToForwardReferencedSupertype, mergeSupertypeTemplateTypes, resolve, setValidator, toAnnotationString, toMaybeEnumElementType, toMaybeEnumType, toMaybeFunctionType, toMaybeFunctionType, toMaybeNamedType, toMaybeObjectType, toMaybeRecordType, toMaybeTemplateType, toMaybeTemplatizedType, toObjectType, toString
-
Method Details
-
builder
Creates aUnionType.Builderfor a newUnionType. -
getAlternates
Gets the alternate types of this union type.- Returns:
- The alternate types of this union type. The returned set is immutable.
-
matchesNumberContext
public boolean matchesNumberContext()This predicate is used to test whether a given type can appear in a numeric context, such as an operand of a multiply operator.- Overrides:
matchesNumberContextin classJSType- Returns:
- true if the type can appear in a numeric context.
-
matchesStringContext
public boolean matchesStringContext()This predicate is used to test whether a given type can appear in aStringcontext, such as an operand of a string concat (+) operator.All types have at least the potential for converting to
String. When we add externally defined types, such as a browser OM, we may choose to add types that do not automatically convert toString.- Overrides:
matchesStringContextin classJSType- Returns:
trueif notVoidType
-
matchesSymbolContext
public boolean matchesSymbolContext()This predicate is used to test whether a given type can appear in aSymbolcontext- Overrides:
matchesSymbolContextin classJSType- Returns:
trueif not it maybe a symbol or Symbol object
-
matchesObjectContext
public boolean matchesObjectContext()This predicate is used to test whether a given type can appear in anObjectcontext, such as the expression in awithstatement.Most types we will encounter, except notably
null, have at least the potential for converting toObject. Host defined objects can get peculiar.VOID type is included here because while it is not part of the JavaScript language, functions returning 'void' type can't be used as operands of any operator or statement.
- Overrides:
matchesObjectContextin classJSType- Returns:
trueif the type is notNullTypeorVoidType
-
findPropertyTypeWithoutConsideringTemplateTypes
Description copied from class:JSTypeLooks up a property on this type, but without properly replacing any templates in the result.Subclasses can override this if they need more complicated logic for property lookup than just autoboxing to an object.
This is only for use by
findPropertyType(JSType). Call that method instead if you need to lookup a property on a random JSType- Overrides:
findPropertyTypeWithoutConsideringTemplateTypesin classJSType
-
canBeCalled
public boolean canBeCalled()Description copied from class:JSTypeThis predicate is used to test whether a given type can be used as the 'function' in a function call.- Overrides:
canBeCalledin classJSType- Returns:
trueif this type might be callable.
-
autobox
Description copied from class:JSTypeDereferences a type for property access. Filters null/undefined and autoboxes the resulting type. Never returns null. -
restrictByNotNullOrUndefined
Description copied from class:JSTypeIf this is a union type, returns a union type that does not include the null or undefined type.- Overrides:
restrictByNotNullOrUndefinedin classJSType
-
restrictByNotUndefined
Description copied from class:JSTypeIf this is a union type, returns a union type that does not include the undefined type.- Overrides:
restrictByNotUndefinedin classJSType
-
restrictByNotNull
Description copied from class:JSTypeIf this is a union type, returns a union type that does not include the null type.- Overrides:
restrictByNotNullin classJSType
-
testForEquality
Description copied from class:JSTypeComparesthisandthat.- Overrides:
testForEqualityin classJSType- Returns:
Tri.TRUEif the comparison of values ofthistype andthatalways succeed (such asundefinedcompared tonull)Tri.FALSEif the comparison of values ofthistype andthatalways fails (such asundefinedcompared tonumber)Tri.UNKNOWNif the comparison can succeed or fail depending on the concrete values
-
isNullable
public boolean isNullable()This predicate determines whether objects of this type can have thenullvalue, and therefore can appear in contexts wherenullis expected.- Overrides:
isNullablein classJSType- Returns:
truefor everything butNumberandBooleantypes.
-
isVoidable
public boolean isVoidable()Tests whether this type is voidable.- Overrides:
isVoidablein classJSType
-
isExplicitlyVoidable
public boolean isExplicitlyVoidable()Tests whether this type explicitly allows undefined (as opposed to ? or *).- Overrides:
isExplicitlyVoidablein classJSType
-
isUnknownType
public boolean isUnknownType()- Overrides:
isUnknownTypein classJSType
-
isStruct
public boolean isStruct()Description copied from class:JSTypeReturns true iffthiscan be astruct. UnionType overrides the method, assumethisis not a union here. -
isDict
public boolean isDict()Description copied from class:JSTypeReturns true iffthiscan be adict. UnionType overrides the method, assumethisis not a union here. -
getLeastSupertype
Description copied from class:JSTypeGets the least supertype ofthisandthat. The least supertype is the join (∨) or supremum of both types in the type lattice.Examples:
number ∨ *=*number ∨ Object=(number, Object)Number ∨ Object=Object
- Overrides:
getLeastSupertypein classJSType- Returns:
this ∨ that
-
getPropertyKind
Description copied from class:JSTypeChecks whether the property is present on the object.- Overrides:
getPropertyKindin classJSType- Parameters:
pname- The property name.autobox- Whether to check for the presents on an autoboxed type
-
toMaybeUnionType
Description copied from class:JSTypeDowncasts this to a UnionType, or returns null if this is not a UnionType. Named in honor of Haskell's Maybe type constructor.- Overrides:
toMaybeUnionTypein classJSType
-
isObject
public boolean isObject()Description copied from class:JSTypeTests whether this type is anObject, or any subtype thereof. -
contains
AUnionTypecontains a given type (alternate) iff the member vector contains it.- Parameters:
type- The alternate which might be in this union.- Returns:
trueif the alternate is in the union
-
getRestrictedUnion
Returns a more restricted union type thanthisone, in which all subtypes oftypehave been removed.Examples:
(number,string)restricted bynumberisstring(null, EvalError, URIError)restricted byErrorisnull
- Parameters:
type- the supertype of the types to remove from this union type
-
getRestrictedTypeGivenOutcome
Description copied from class:JSTypeComputes the restricted type of this type knowing that theToBooleanpredicate has a specific value. For more information about theToBooleanpredicate, seeJSType.getPossibleToBooleanOutcomes().- Overrides:
getRestrictedTypeGivenOutcomein classJSType- Parameters:
outcome- the value of theToBooleanpredicate- Returns:
- the restricted type, or the Any Type if the underlying type could not have yielded this ToBoolean value TODO(user): Move this method to the SemanticRAI and use the visit method of types to get the restricted type.
-
getPossibleToBooleanOutcomes
Description copied from class:JSTypeComputes the set of possible outcomes of theToBooleanpredicate for this type. TheToBooleanpredicate is defined by the ECMA-262 standard, 3rd edition. Its behavior for simple types can be summarized by the following table:ToBoolean results by input type type result undefined{false} null{false} boolean{true, false} number{true, false} string{true, false} Object{true} - Specified by:
getPossibleToBooleanOutcomesin classJSType- Returns:
- the set of boolean literals for this type
-
getTypesUnderEquality
Description copied from class:JSTypeComputes the subset ofthisandthattypes if equality is observed. If a valuev1of typenullis equal to a valuev2of type(undefined,number), we can infer that the type ofv1isnulland the type ofv2isundefined.- Overrides:
getTypesUnderEqualityin classJSType- Returns:
- a pair containing the restricted type of
thisas the first component and the restricted type ofthatas the second element. The returned pair is nevernulleven though its components may benull
-
getTypesUnderInequality
Description copied from class:JSTypeComputes the subset ofthisandthattypes if inequality is observed. If a valuev1of typenumberis not equal to a valuev2of type(undefined,number), we can infer that the type ofv1isnumberand the type ofv2isnumberas well.- Overrides:
getTypesUnderInequalityin classJSType- Returns:
- a pair containing the restricted type of
thisas the first component and the restricted type ofthatas the second element. The returned pair is nevernulleven though its components may benull
-
getTypesUnderShallowInequality
Description copied from class:JSTypeComputes the subset ofthisandthattypes under shallow inequality.- Overrides:
getTypesUnderShallowInequalityin classJSType- Returns:
- A pair containing the restricted type of
thisas the first component and the restricted type ofthatas the second element. The returned pair is nevernulleven though its components may benull
-
visit
Description copied from class:JSTypeVisit this type with the given visitor. -
collapseUnion
Description copied from class:JSTypeGets the least supertype of this that's not a union.- Overrides:
collapseUnionin classJSType
-
matchConstraint
Description copied from class:JSTypeModify this type so that it matches the specified type.This is useful for reverse type-inference, where we want to infer that an object literal matches its constraint (much like how the java compiler does reverse-inference to figure out generics).
- Overrides:
matchConstraintin classJSType
-
hasAnyTemplateTypesInternal
public boolean hasAnyTemplateTypesInternal()
-