Strict optional properties (#43947)

* Introduce --strictOptionalProperties compiler switch

* Accept new baselines

* Removing missingType when printing back optional properties

* Accept new baselines

* Fix linting issue

* Use getNonMissingTypeOfSymbol in getTypeOfSymbolAtLocation

* Properly elaborate errors involving optional properties

* Accept new baselines

* Properly check optional properties in tuple types

* Accept new baselines

* Add missing tuple type check

* More permissive check of strict optional properties and index signatures

* Add tests

* Fix lint issues

* Accept new baselines
This commit is contained in:
Anders Hejlsberg authored and GitHub committed 2021-06-01 14:52:16 -07:00
1 parent b603a04eed
commit 391f9ffb85
90 files changed
+2965 -787

No files matched your search

+101 -83
View File
@@ -343,6 +343,7 @@ namespace ts {
const strictFunctionTypes = getStrictOptionValue(compilerOptions, "strictFunctionTypes");
const strictBindCallApply = getStrictOptionValue(compilerOptions, "strictBindCallApply");
const strictPropertyInitialization = getStrictOptionValue(compilerOptions, "strictPropertyInitialization");
const strictOptionalProperties = getStrictOptionValue(compilerOptions, "strictOptionalProperties");
const noImplicitAny = getStrictOptionValue(compilerOptions, "noImplicitAny");
const noImplicitThis = getStrictOptionValue(compilerOptions, "noImplicitThis");
const keyofStringsOnly = !!compilerOptions.keyofStringsOnly;
@@ -736,6 +737,7 @@ namespace ts {
const undefinedType = createIntrinsicType(TypeFlags.Undefined, "undefined");
const undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(TypeFlags.Undefined, "undefined", ObjectFlags.ContainsWideningType);
const optionalType = createIntrinsicType(TypeFlags.Undefined, "undefined");
const missingType = strictOptionalProperties ? createIntrinsicType(TypeFlags.Undefined, "undefined") : undefinedType;
const nullType = createIntrinsicType(TypeFlags.Null, "null");
const nullWideningType = strictNullChecks ? nullType : createIntrinsicType(TypeFlags.Null, "null", ObjectFlags.ContainsWideningType);
const stringType = createIntrinsicType(TypeFlags.String, "string");
@@ -4806,7 +4808,7 @@ namespace ts {
}
const typeParameterNode = typeParameterToDeclarationWithConstraint(getTypeParameterFromMappedType(type), context, appropriateConstraintTypeNode);
const nameTypeNode = type.declaration.nameType ? typeToTypeNodeHelper(getNameTypeFromMappedType(type)!, context) : undefined;
const templateTypeNode = typeToTypeNodeHelper(getTemplateTypeFromMappedType(type), context);
const templateTypeNode = typeToTypeNodeHelper(removeMissingType(getTemplateTypeFromMappedType(type), !!(getMappedTypeModifiers(type) & MappedTypeModifiers.IncludeOptional)), context);
const mappedTypeNode = factory.createMappedTypeNode(readonlyToken, typeParameterNode, nameTypeNode, questionToken, templateTypeNode);
context.approximateLength += 10;
return setEmitFlags(mappedTypeNode, EmitFlags.SingleLine);
@@ -4986,7 +4988,7 @@ namespace ts {
}
function typeReferenceToTypeNode(type: TypeReference) {
const typeArguments: readonly Type[] = getTypeArguments(type);
let typeArguments: readonly Type[] = getTypeArguments(type);
if (type.target === globalArrayType || type.target === globalReadonlyArrayType) {
if (context.flags & NodeBuilderFlags.WriteArrayAsGenericType) {
const typeArgumentNode = typeToTypeNodeHelper(typeArguments[0], context);
@@ -4997,6 +4999,7 @@ namespace ts {
return type.target === globalArrayType ? arrayType : factory.createTypeOperatorNode(SyntaxKind.ReadonlyKeyword, arrayType);
}
else if (type.target.objectFlags & ObjectFlags.Tuple) {
typeArguments = sameMap(typeArguments, (t, i) => removeMissingType(t, !!((type.target as TupleType).elementFlags[i] & ElementFlags.Optional)));
if (typeArguments.length > 0) {
const arity = getTypeReferenceArity(type);
const tupleConstituentNodes = mapToTypeNodes(typeArguments.slice(0, arity), context);
@@ -5229,7 +5232,7 @@ namespace ts {
function addPropertyToElementList(propertySymbol: Symbol, context: NodeBuilderContext, typeElements: TypeElement[]) {
const propertyIsReverseMapped = !!(getCheckFlags(propertySymbol) & CheckFlags.ReverseMapped);
const propertyType = shouldUsePlaceholderForProperty(propertySymbol, context) ?
anyType : getTypeOfSymbol(propertySymbol);
anyType : getNonMissingTypeOfSymbol(propertySymbol);
const saveEnclosingDeclaration = context.enclosingDeclaration;
context.enclosingDeclaration = undefined;
if (context.tracker.trackSymbol && getCheckFlags(propertySymbol) & CheckFlags.Late && isLateBoundName(propertySymbol.escapedName)) {
@@ -8365,8 +8368,8 @@ namespace ts {
return expr.kind === SyntaxKind.ArrayLiteralExpression && (expr as ArrayLiteralExpression).elements.length === 0;
}
function addOptionality(type: Type, optional = true): Type {
return strictNullChecks && optional ? getOptionalType(type) : type;
function addOptionality(type: Type, isProperty = false, isOptional = true): Type {
return strictNullChecks && isOptional ? getOptionalType(type, isProperty) : type;
}
// Return the inferred type for a variable, parameter, or property declaration
@@ -8391,15 +8394,16 @@ namespace ts {
return getTypeForBindingElement(declaration as BindingElement);
}
const isProperty = isPropertyDeclaration(declaration) || isPropertySignature(declaration);
const isOptional = includeOptionality && (
isParameter(declaration) && isJSDocOptionalParameter(declaration)
|| isOptionalJSDocPropertyLikeTag(declaration)
|| !isBindingElement(declaration) && !isVariableDeclaration(declaration) && !!declaration.questionToken);
isProperty && !!(declaration as PropertyDeclaration | PropertySignature).questionToken ||
isParameter(declaration) && (!!declaration.questionToken || isJSDocOptionalParameter(declaration)) ||
isOptionalJSDocPropertyLikeTag(declaration));
// Use type from type annotation if one is present
const declaredType = tryGetTypeFromEffectiveTypeNode(declaration);
if (declaredType) {
return addOptionality(declaredType, isOptional);
return addOptionality(declaredType, isProperty, isOptional);
}
if ((noImplicitAny || isInJSFile(declaration)) &&
@@ -8445,7 +8449,7 @@ namespace ts {
// Use contextual parameter type if one is available
const type = declaration.symbol.escapedName === InternalSymbolName.This ? getContextualThisParameterType(func) : getContextuallyTypedParameterType(declaration);
if (type) {
return addOptionality(type, isOptional);
return addOptionality(type, /*isProperty*/ false, isOptional);
}
}
@@ -8459,7 +8463,7 @@ namespace ts {
}
}
const type = widenTypeInferredFromInitializer(declaration, checkDeclarationInitializer(declaration));
return addOptionality(type, isOptional);
return addOptionality(type, isProperty, isOptional);
}
if (isPropertyDeclaration(declaration) && !hasStaticModifier(declaration) && (noImplicitAny || isInJSFile(declaration))) {
@@ -8469,7 +8473,7 @@ namespace ts {
const type = constructor ? getFlowTypeInConstructor(declaration.symbol, constructor) :
getEffectiveModifierFlags(declaration) & ModifierFlags.Ambient ? getTypeOfPropertyInBaseClass(declaration.symbol) :
undefined;
return type && addOptionality(type, isOptional);
return type && addOptionality(type, /*isProperty*/ true, isOptional);
}
if (isJsxAttribute(declaration)) {
@@ -8636,7 +8640,7 @@ namespace ts {
type = getUnionType(sourceTypes!, UnionReduction.Subtype);
}
}
const widened = getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor));
const widened = getWidenedType(addOptionality(type, /*isProperty*/ false, definedInMethod && !definedInConstructor));
if (symbol.valueDeclaration && filterType(widened, t => !!(t.flags & ~TypeFlags.Nullable)) === neverType) {
reportImplicitAny(symbol.valueDeclaration, anyType);
return anyType;
@@ -8679,7 +8683,10 @@ namespace ts {
if (symbol.parent?.valueDeclaration) {
const typeNode = getEffectiveTypeAnnotationNode(symbol.parent.valueDeclaration);
if (typeNode) {
return getTypeOfPropertyOfType(getTypeFromTypeNode(typeNode), symbol.escapedName);
const annotationSymbol = getPropertyOfType(getTypeFromTypeNode(typeNode), symbol.escapedName);
if (annotationSymbol) {
return getNonMissingTypeOfSymbol(annotationSymbol);
}
}
}
@@ -9384,6 +9391,10 @@ namespace ts {
return errorType;
}
function getNonMissingTypeOfSymbol(symbol: Symbol) {
return removeMissingType(getTypeOfSymbol(symbol), !!(symbol.flags & SymbolFlags.Optional));
}
function isReferenceToType(type: Type, target: Type) {
return type !== undefined
&& target !== undefined
@@ -11168,7 +11179,7 @@ namespace ts {
// When creating an optional property in strictNullChecks mode, if 'undefined' isn't assignable to the
// type, we include 'undefined' in the type. Similarly, when creating a non-optional property in strictNullChecks
// mode, if the underlying property is optional we remove 'undefined' from the type.
let type = strictNullChecks && symbol.flags & SymbolFlags.Optional && !maybeTypeOfKind(propType, TypeFlags.Undefined | TypeFlags.Void) ? getOptionalType(propType) :
let type = strictNullChecks && symbol.flags & SymbolFlags.Optional && !maybeTypeOfKind(propType, TypeFlags.Undefined | TypeFlags.Void) ? getOptionalType(propType, /*isProperty*/ true) :
symbol.checkFlags & CheckFlags.StripOptional ? getTypeWithFacts(propType, TypeFacts.NEUndefined) :
propType;
if (!popTypeResolution()) {
@@ -11199,7 +11210,7 @@ namespace ts {
function getTemplateTypeFromMappedType(type: MappedType) {
return type.templateType ||
(type.templateType = type.declaration.type ?
instantiateType(addOptionality(getTypeFromTypeNode(type.declaration.type), !!(getMappedTypeModifiers(type) & MappedTypeModifiers.IncludeOptional)), type.mapper) :
instantiateType(addOptionality(getTypeFromTypeNode(type.declaration.type), /*isProperty*/ true, !!(getMappedTypeModifiers(type) & MappedTypeModifiers.IncludeOptional)), type.mapper) :
errorType);
}
@@ -13680,8 +13691,7 @@ namespace ts {
}
function getTypeFromOptionalTypeNode(node: OptionalTypeNode): Type {
const type = getTypeFromTypeNode(node.type);
return strictNullChecks ? getOptionalType(type) : type;
return addOptionality(getTypeFromTypeNode(node.type), /*isProperty*/ true);
}
function getTypeId(type: Type): TypeId {
@@ -13871,6 +13881,12 @@ namespace ts {
if (includes & TypeFlags.AnyOrUnknown) {
return includes & TypeFlags.Any ? includes & TypeFlags.IncludesWildcard ? wildcardType : anyType : unknownType;
}
if (strictOptionalProperties && includes & TypeFlags.Undefined) {
const missingIndex = binarySearch(typeSet, missingType, getTypeId, compareValues);
if (missingIndex >= 0 && containsType(typeSet, undefinedType)) {
orderedRemoveItemAt(typeSet, missingIndex);
}
}
if (includes & (TypeFlags.Literal | TypeFlags.UniqueESSymbol) || includes & TypeFlags.Void && includes & TypeFlags.Undefined) {
removeRedundantLiteralTypes(typeSet, includes, !!(unionReduction & UnionReduction.Subtype));
}
@@ -15390,7 +15406,7 @@ namespace ts {
const isSetonlyAccessor = prop.flags & SymbolFlags.SetAccessor && !(prop.flags & SymbolFlags.GetAccessor);
const flags = SymbolFlags.Property | SymbolFlags.Optional;
const result = createSymbol(flags, prop.escapedName, getIsLateCheckFlag(prop) | (readonly ? CheckFlags.Readonly : 0));
result.type = isSetonlyAccessor ? undefinedType : getUnionType([getTypeOfSymbol(prop), undefinedType]);
result.type = isSetonlyAccessor ? undefinedType : addOptionality(getTypeOfSymbol(prop), /*isProperty*/ true);
result.declarations = prop.declarations;
result.nameType = getSymbolLinks(prop).nameType;
result.syntheticOrigin = prop;
@@ -15688,8 +15704,7 @@ namespace ts {
const links = getNodeLinks(node);
return links.resolvedType || (links.resolvedType =
node.dotDotDotToken ? getTypeFromRestTypeNode(node) :
node.questionToken && strictNullChecks ? getOptionalType(getTypeFromTypeNode(node.type)) :
getTypeFromTypeNode(node.type));
addOptionality(getTypeFromTypeNode(node.type), /*isProperty*/ true, !!node.questionToken));
}
function getTypeFromTypeNode(node: TypeNode): Type {
@@ -16154,7 +16169,7 @@ namespace ts {
const templateMapper = appendTypeMapping(mapper, getTypeParameterFromMappedType(type), key);
const propType = instantiateType(getTemplateTypeFromMappedType(type.target as MappedType || type), templateMapper);
const modifiers = getMappedTypeModifiers(type);
return strictNullChecks && modifiers & MappedTypeModifiers.IncludeOptional && !maybeTypeOfKind(propType, TypeFlags.Undefined | TypeFlags.Void) ? getOptionalType(propType) :
return strictNullChecks && modifiers & MappedTypeModifiers.IncludeOptional && !maybeTypeOfKind(propType, TypeFlags.Undefined | TypeFlags.Void) ? getOptionalType(propType, /*isProperty*/ true) :
strictNullChecks && modifiers & MappedTypeModifiers.ExcludeOptional && isOptional ? getTypeWithFacts(propType, TypeFacts.NEUndefined) :
propType;
}
@@ -16700,10 +16715,16 @@ namespace ts {
let reportedError = false;
for (let status = iterator.next(); !status.done; status = iterator.next()) {
const { errorNode: prop, innerExpression: next, nameType, errorMessage } = status.value;
const targetPropType = getBestMatchIndexedAccessTypeOrUndefined(source, target, nameType);
let targetPropType = getBestMatchIndexedAccessTypeOrUndefined(source, target, nameType);
if (!targetPropType || targetPropType.flags & TypeFlags.IndexedAccess) continue; // Don't elaborate on indexes on generic variables
const sourcePropType = getIndexedAccessTypeOrUndefined(source, nameType);
if (sourcePropType && !checkTypeRelatedTo(sourcePropType, targetPropType, relation, /*errorNode*/ undefined)) {
let sourcePropType = getIndexedAccessTypeOrUndefined(source, nameType);
if (!sourcePropType) continue;
const propName = getPropertyNameFromIndex(nameType, /*accessNode*/ undefined);
const targetIsOptional = !!(propName && (getPropertyOfType(target, propName) || unknownSymbol).flags & SymbolFlags.Optional);
const sourceIsOptional = !!(propName && (getPropertyOfType(source, propName) || unknownSymbol).flags & SymbolFlags.Optional);
targetPropType = removeMissingType(targetPropType, targetIsOptional);
sourcePropType = removeMissingType(sourcePropType, targetIsOptional && sourceIsOptional);
if (!checkTypeRelatedTo(sourcePropType, targetPropType, relation, /*errorNode*/ undefined)) {
const elaborated = next && elaborateError(next, sourcePropType, targetPropType, relation, /*headMessage*/ undefined, containingMessageChain, errorOutputContainer);
if (elaborated) {
reportedError = true;
@@ -18879,7 +18900,7 @@ namespace ts {
// fixed limit before incurring the cost of any allocations:
let numCombinations = 1;
for (const sourceProperty of sourcePropertiesFiltered) {
numCombinations *= countTypes(getTypeOfSymbol(sourceProperty));
numCombinations *= countTypes(getNonMissingTypeOfSymbol(sourceProperty));
if (numCombinations > 25) {
// We've reached the complexity limit.
tracing?.instant(tracing.Phase.CheckTypes, "typeRelatedToDiscriminatedType_DepthLimit", { sourceId: source.id, targetId: target.id, numCombinations });
@@ -18892,7 +18913,7 @@ namespace ts {
const excludedProperties = new Set<__String>();
for (let i = 0; i < sourcePropertiesFiltered.length; i++) {
const sourceProperty = sourcePropertiesFiltered[i];
const sourcePropertyType = getTypeOfSymbol(sourceProperty);
const sourcePropertyType = getNonMissingTypeOfSymbol(sourceProperty);
sourceDiscriminantTypes[i] = sourcePropertyType.flags & TypeFlags.Union
? (sourcePropertyType as UnionType).types
: [sourcePropertyType];
@@ -18973,45 +18994,9 @@ namespace ts {
function isPropertySymbolTypeRelated(sourceProp: Symbol, targetProp: Symbol, getTypeOfSourceProperty: (sym: Symbol) => Type, reportErrors: boolean, intersectionState: IntersectionState): Ternary {
const targetIsOptional = strictNullChecks && !!(getCheckFlags(targetProp) & CheckFlags.Partial);
const source = getTypeOfSourceProperty(sourceProp);
if (getCheckFlags(targetProp) & CheckFlags.DeferredType && !getSymbolLinks(targetProp).type) {
// Rather than resolving (and normalizing) the type, relate constituent-by-constituent without performing normalization or seconadary passes
const links = getSymbolLinks(targetProp);
Debug.assertIsDefined(links.deferralParent);
Debug.assertIsDefined(links.deferralConstituents);
const unionParent = !!(links.deferralParent.flags & TypeFlags.Union);
let result = unionParent ? Ternary.False : Ternary.True;
const targetTypes = links.deferralConstituents;
for (const targetType of targetTypes) {
const related = isRelatedTo(source, targetType, /*reportErrors*/ false, /*headMessage*/ undefined, unionParent ? 0 : IntersectionState.Target);
if (!unionParent) {
if (!related) {
// Can't assign to a target individually - have to fallback to assigning to the _whole_ intersection (which forces normalization)
return isRelatedTo(source, addOptionality(getTypeOfSymbol(targetProp), targetIsOptional), reportErrors);
}
result &= related;
}
else {
if (related) {
return related;
}
}
}
if (unionParent && !result && targetIsOptional) {
result = isRelatedTo(source, undefinedType);
}
if (unionParent && !result && reportErrors) {
// The easiest way to get the right errors here is to un-defer (which may be costly)
// If it turns out this is too costly too often, we can replicate the error handling logic within
// typeRelatedToSomeType without the discriminatable type branch (as that requires a manifest union
// type on which to hand discriminable properties, which we are expressly trying to avoid here)
return isRelatedTo(source, addOptionality(getTypeOfSymbol(targetProp), targetIsOptional), reportErrors);
}
return result;
}
else {
return isRelatedTo(source, addOptionality(getTypeOfSymbol(targetProp), targetIsOptional), reportErrors, /*headMessage*/ undefined, intersectionState);
}
const effectiveTarget = addOptionality(getNonMissingTypeOfSymbol(targetProp), /*isProperty*/ false, targetIsOptional);
const effectiveSource = getTypeOfSourceProperty(sourceProp);
return isRelatedTo(effectiveSource, effectiveTarget, reportErrors, /*headMessage*/ undefined, intersectionState);
}
function propertyRelatedTo(source: Type, target: Type, sourceProp: Symbol, targetProp: Symbol, getTypeOfSourceProperty: (sym: Symbol) => Type, reportErrors: boolean, intersectionState: IntersectionState, skipOptional: boolean): Ternary {
@@ -19152,7 +19137,7 @@ namespace ts {
}
return Ternary.False;
}
if (!targetRestFlag && sourceRestFlag) {
if (!targetRestFlag && (sourceRestFlag || targetArity < sourceArity)) {
if (reportErrors) {
if (sourceMinLength < targetMinLength) {
reportError(Diagnostics.Target_requires_0_element_s_but_source_may_have_fewer, targetMinLength);
@@ -19200,10 +19185,11 @@ namespace ts {
}
}
const sourceType = !isTupleType(source) ? sourceTypeArguments[0] :
i < startCount || i >= targetArity - endCount ? sourceTypeArguments[sourceIndex] :
i < startCount || i >= targetArity - endCount ? removeMissingType(sourceTypeArguments[sourceIndex], !!(sourceFlags & targetFlags & ElementFlags.Optional)) :
getElementTypeOfSliceOfTupleType(source, startCount, endCount) || neverType;
const targetType = targetTypeArguments[i];
const targetCheckType = sourceFlags & ElementFlags.Variadic && targetFlags & ElementFlags.Rest ? createArrayType(targetType) : targetType;
const targetCheckType = sourceFlags & ElementFlags.Variadic && targetFlags & ElementFlags.Rest ? createArrayType(targetType) :
removeMissingType(targetType, !!(targetFlags & ElementFlags.Optional));
const related = isRelatedTo(sourceType, targetCheckType, reportErrors, /*headMessage*/ undefined, intersectionState);
if (!related) {
if (reportErrors) {
@@ -19236,7 +19222,7 @@ namespace ts {
for (const sourceProp of excludeProperties(getPropertiesOfType(source), excludedProperties)) {
if (!getPropertyOfObjectType(target, sourceProp.escapedName)) {
const sourceType = getTypeOfSymbol(sourceProp);
if (!(sourceType === undefinedType || sourceType === undefinedWideningType || sourceType === optionalType)) {
if (!(sourceType.flags & TypeFlags.Undefined)) {
if (reportErrors) {
reportError(Diagnostics.Property_0_does_not_exist_on_type_1, symbolToString(sourceProp), typeToString(target));
}
@@ -19254,7 +19240,7 @@ namespace ts {
if (!(targetProp.flags & SymbolFlags.Prototype) && (!numericNamesOnly || isNumericLiteralName(name) || name === "length")) {
const sourceProp = getPropertyOfType(source, name);
if (sourceProp && sourceProp !== targetProp) {
const related = propertyRelatedTo(source, target, sourceProp, targetProp, getTypeOfSymbol, reportErrors, intersectionState, relation === comparableRelation);
const related = propertyRelatedTo(source, target, sourceProp, targetProp, getNonMissingTypeOfSymbol, reportErrors, intersectionState, relation === comparableRelation);
if (!related) {
return Ternary.False;
}
@@ -20321,9 +20307,9 @@ namespace ts {
getUnionType([type, undefinedType, nullType]);
}
function getOptionalType(type: Type): Type {
function getOptionalType(type: Type, isProperty = false): Type {
Debug.assert(strictNullChecks);
return type.flags & TypeFlags.Undefined ? type : getUnionType([type, undefinedType]);
return type.flags & TypeFlags.Undefined ? type : getUnionType([type, isProperty ? missingType : undefinedType]);
}
function getGlobalNonNullableTypeInstantiation(type: Type) {
@@ -20366,6 +20352,14 @@ namespace ts {
exprType;
}
function removeMissingType(type: Type, isOptional: boolean) {
return strictOptionalProperties && isOptional ? filterType(type, t => t !== missingType) : type;
}
function containsMissingType(type: Type) {
return strictOptionalProperties && (type === missingType || type.flags & TypeFlags.Union && containsType((type as UnionType).types, missingType));
}
/**
* Is source potentially coercible to target type under `==`.
* Assumes that `source` is a constituent of a union, hence
@@ -20509,7 +20503,7 @@ namespace ts {
if (cached) {
return cached;
}
const result = createSymbolWithType(prop, undefinedType);
const result = createSymbolWithType(prop, missingType);
result.flags |= SymbolFlags.Optional;
undefinedProperties.set(prop.escapedName, result);
return result;
@@ -23574,8 +23568,14 @@ namespace ts {
return narrowTypeByInstanceof(type, expr, assumeTrue);
case SyntaxKind.InKeyword:
const target = getReferenceCandidate(expr.right);
if (isStringLiteralLike(expr.left) && isMatchingReference(reference, target)) {
return narrowByInKeyword(type, expr.left, assumeTrue);
if (isStringLiteralLike(expr.left)) {
if (containsMissingType(type) && isAccessExpression(reference) && isMatchingReference(reference.expression, target) &&
getAccessedPropertyName(reference) === escapeLeadingUnderscores(expr.left.text)) {
return getTypeWithFacts(type, assumeTrue ? TypeFacts.NEUndefined : TypeFacts.EQUndefined);
}
if (isMatchingReference(reference, target)) {
return narrowByInKeyword(type, expr.left, assumeTrue);
}
}
break;
case SyntaxKind.CommaToken:
@@ -23961,6 +23961,16 @@ namespace ts {
return narrowTypeByTypePredicate(type, predicate, callExpression, assumeTrue);
}
}
if (containsMissingType(type) && isAccessExpression(reference) && isPropertyAccessExpression(callExpression.expression)) {
const callAccess = callExpression.expression;
if (isMatchingReference(reference.expression, getReferenceCandidate(callAccess.expression)) &&
isIdentifier(callAccess.name) && callAccess.name.escapedText === "hasOwnProperty" && callExpression.arguments.length === 1) {
const argument = callExpression.arguments[0];
if (isStringLiteralLike(argument) && getAccessedPropertyName(reference) === escapeLeadingUnderscores(argument.text)) {
return getTypeWithFacts(type, assumeTrue ? TypeFacts.NEUndefined : TypeFacts.EQUndefined);
}
}
}
return type;
}
@@ -24052,7 +24062,7 @@ namespace ts {
// to it at the given location. Since we have no control flow information for the
// hypothetical reference (control flow information is created and attached by the
// binder), we simply return the declared type of the symbol.
return getTypeOfSymbol(symbol);
return getNonMissingTypeOfSymbol(symbol);
}
function getControlFlowContainer(node: Node): Node {
@@ -26018,6 +26028,7 @@ namespace ts {
const contextualType = getApparentTypeOfContextualType(node);
const inDestructuringPattern = isAssignmentTarget(node);
const inConstContext = isConstContext(node);
let hasOmittedExpression = false;
for (let i = 0; i < elementCount; i++) {
const e = elements[i];
if (e.kind === SyntaxKind.SpreadElement) {
@@ -26053,11 +26064,16 @@ namespace ts {
elementFlags.push(ElementFlags.Rest);
}
}
else if (strictOptionalProperties && e.kind === SyntaxKind.OmittedExpression) {
hasOmittedExpression = true;
elementTypes.push(missingType);
elementFlags.push(ElementFlags.Optional);
}
else {
const elementContextualType = getContextualTypeForElementExpression(contextualType, elementTypes.length);
const type = checkExpressionForMutableLocation(e, checkMode, elementContextualType, forceTuple);
elementTypes.push(type);
elementFlags.push(ElementFlags.Required);
elementTypes.push(addOptionality(type, /*isProperty*/ true, hasOmittedExpression));
elementFlags.push(hasOmittedExpression ? ElementFlags.Optional : ElementFlags.Required);
}
}
if (inDestructuringPattern) {
@@ -27482,8 +27498,10 @@ namespace ts {
// assignment target, and the referenced property was declared as a variable, property,
// accessor, or optional method.
const assignmentKind = getAssignmentTargetKind(node);
if (assignmentKind === AssignmentKind.Definite ||
prop &&
if (assignmentKind === AssignmentKind.Definite) {
return removeMissingType(propType, !!(prop && prop.flags & SymbolFlags.Optional));
}
if (prop &&
!(prop.flags & (SymbolFlags.Variable | SymbolFlags.Property | SymbolFlags.Accessor))
&& !(prop.flags & SymbolFlags.Method && propType.flags & TypeFlags.Union)
&& !isDuplicatedCommonJSExport(prop.declarations)) {
@@ -36890,7 +36908,7 @@ namespace ts {
if (stringIndexType || numberIndexType) {
forEach(getPropertiesOfObjectType(type), prop => {
if (isStatic && prop.flags & SymbolFlags.Prototype) return;
const propType = getTypeOfSymbol(prop);
const propType = getNonMissingTypeOfSymbol(prop);
checkIndexConstraintForProperty(prop, propType, type, declaredStringIndexer, stringIndexType, IndexKind.String);
checkIndexConstraintForProperty(prop, propType, type, declaredNumberIndexer, numberIndexType, IndexKind.Number);
});
@@ -36903,7 +36921,7 @@ namespace ts {
// and properties with literal names were already checked.
if (!hasSyntacticModifier(member, ModifierFlags.Static) && !hasBindableName(member)) {
const symbol = getSymbolOfNode(member);
const propType = getTypeOfSymbol(symbol);
const propType = getNonMissingTypeOfSymbol(symbol);
checkIndexConstraintForProperty(symbol, propType, type, declaredStringIndexer, stringIndexType, IndexKind.String);
checkIndexConstraintForProperty(symbol, propType, type, declaredNumberIndexer, numberIndexType, IndexKind.Number);
}
+9
View File
@@ -612,6 +612,15 @@ namespace ts {
category: Diagnostics.Strict_Type_Checking_Options,
description: Diagnostics.Enable_strict_checking_of_property_initialization_in_classes
},
{
name: "strictOptionalProperties",
type: "boolean",
affectsSemanticDiagnostics: true,
strictFlag: true,
showInSimplifiedHelpView: true,
category: Diagnostics.Strict_Type_Checking_Options,
description: Diagnostics.Enable_strict_checking_of_optional_properties
},
{
name: "noImplicitThis",
type: "boolean",
+4
View File
@@ -4877,6 +4877,10 @@
"category": "Message",
"code": 6242
},
"Enable strict checking of optional properties.": {
"category": "Message",
"code": 6243
},
"Projects to reference": {
"category": "Message",
+3
View File
@@ -3043,6 +3043,9 @@ namespace ts {
if (options.strictPropertyInitialization && !getStrictOptionValue(options, "strictNullChecks")) {
createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "strictPropertyInitialization", "strictNullChecks");
}
if (options.strictOptionalProperties && !getStrictOptionValue(options, "strictNullChecks")) {
createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "strictOptionalProperties", "strictNullChecks");
}
if (options.isolatedModules) {
if (options.out) {
+1
View File
@@ -6041,6 +6041,7 @@ namespace ts {
strictBindCallApply?: boolean; // Always combine with strict property
strictNullChecks?: boolean; // Always combine with strict property
strictPropertyInitialization?: boolean; // Always combine with strict property
strictOptionalProperties?: boolean; // Always combine with strict property
stripInternal?: boolean;
suppressExcessPropertyErrors?: boolean;
suppressImplicitAnyIndexErrors?: boolean;
+1
View File
@@ -6086,6 +6086,7 @@ namespace ts {
| "strictFunctionTypes"
| "strictBindCallApply"
| "strictPropertyInitialization"
| "strictOptionalProperties"
| "alwaysStrict"
;