diff --git a/package-lock.json b/package-lock.json index da66611d5bb..e9fbb2e5700 100644 --- a/package-lock.json +++ b/package-lock.json @@ -638,9 +638,9 @@ "dev": true }, "@types/node": { - "version": "17.0.21", - "resolved": "https://registry.npmjs.org/@types/node/-/node-17.0.21.tgz", - "integrity": "sha512-DBZCJbhII3r90XbQxI8Y9IjjiiOGlZ0Hr32omXIZvwwZ7p4DMMXGrKXVyPfuoBOri9XNtL0UK69jYIBIsRX3QQ==", + "version": "17.0.23", + "resolved": "https://registry.npmjs.org/@types/node/-/node-17.0.23.tgz", + "integrity": "sha512-UxDxWn7dl97rKVeVS61vErvw086aCYhDLyvRQZ5Rk65rZKepaFdm53GeqXaKBuOhED4e9uWq34IC3TdSdJJ2Gw==", "dev": true }, "@types/node-fetch": { @@ -4202,9 +4202,9 @@ } }, "minimist": { - "version": "1.2.5", - "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.5.tgz", - "integrity": "sha512-FM9nNUYrRBAELZQT3xeZQ7fmMOBg6nWNmJKTcgsJeaLstP/UODVpGsr5OhXhhXg6f+qtJ8uiZ+PUxkDWcgIXLw==", + "version": "1.2.6", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.6.tgz", + "integrity": "sha512-Jsjnk4bw3YJqYzbdyBiNsPWHPfO++UGG749Cxs6peCu5Xg4nrena6OVxOYxrQTqww0Jmwt+Ref8rggumkTLz9Q==", "dev": true }, "mixin-deep": { diff --git a/src/compiler/binder.ts b/src/compiler/binder.ts index 82ae4ba3480..a5dc3db10bc 100644 --- a/src/compiler/binder.ts +++ b/src/compiler/binder.ts @@ -657,11 +657,15 @@ namespace ts { const saveExceptionTarget = currentExceptionTarget; const saveActiveLabelList = activeLabelList; const saveHasExplicitReturn = hasExplicitReturn; - const isIIFE = containerFlags & ContainerFlags.IsFunctionExpression && !hasSyntacticModifier(node, ModifierFlags.Async) && - !(node as FunctionLikeDeclaration).asteriskToken && !!getImmediatelyInvokedFunctionExpression(node); + const isImmediatelyInvoked = + (containerFlags & ContainerFlags.IsFunctionExpression && + !hasSyntacticModifier(node, ModifierFlags.Async) && + !(node as FunctionLikeDeclaration).asteriskToken && + !!getImmediatelyInvokedFunctionExpression(node)) || + node.kind === SyntaxKind.ClassStaticBlockDeclaration; // A non-async, non-generator IIFE is considered part of the containing control flow. Return statements behave // similarly to break statements that exit to a label just past the statement body. - if (!isIIFE) { + if (!isImmediatelyInvoked) { currentFlow = initFlowNode({ flags: FlowFlags.Start }); if (containerFlags & (ContainerFlags.IsFunctionExpression | ContainerFlags.IsObjectLiteralOrClassExpressionMethodOrAccessor)) { currentFlow.node = node as FunctionExpression | ArrowFunction | MethodDeclaration | GetAccessorDeclaration | SetAccessorDeclaration; @@ -669,7 +673,7 @@ namespace ts { } // We create a return control flow graph for IIFEs and constructors. For constructors // we use the return control flow graph in strict property initialization checks. - currentReturnTarget = isIIFE || node.kind === SyntaxKind.Constructor || node.kind === SyntaxKind.ClassStaticBlockDeclaration || (isInJSFile(node) && (node.kind === SyntaxKind.FunctionDeclaration || node.kind === SyntaxKind.FunctionExpression)) ? createBranchLabel() : undefined; + currentReturnTarget = isImmediatelyInvoked || node.kind === SyntaxKind.Constructor || (isInJSFile(node) && (node.kind === SyntaxKind.FunctionDeclaration || node.kind === SyntaxKind.FunctionExpression)) ? createBranchLabel() : undefined; currentExceptionTarget = undefined; currentBreakTarget = undefined; currentContinueTarget = undefined; @@ -695,7 +699,7 @@ namespace ts { (node as FunctionLikeDeclaration | ClassStaticBlockDeclaration).returnFlowNode = currentFlow; } } - if (!isIIFE) { + if (!isImmediatelyInvoked) { currentFlow = saveCurrentFlow; } currentBreakTarget = saveBreakTarget; diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 6268e17945c..bbf3dbe7c17 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -172,6 +172,7 @@ namespace ts { EnumTagType, ResolvedTypeArguments, ResolvedBaseTypes, + WriteType, } const enum CheckMode { @@ -305,7 +306,7 @@ namespace ts { (preserveConstEnums && moduleState === ModuleInstanceState.ConstEnumOnly); } - export function createTypeChecker(host: TypeCheckerHost, produceDiagnostics: boolean): TypeChecker { + export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const getPackagesMap = memoize(() => { // A package name maps to true when we detect it has .d.ts files. // This is useful as an approximation of whether a package bundles its own types. @@ -322,6 +323,12 @@ namespace ts { return map; }); + let deferredDiagnosticsCallbacks: (() => void)[] = []; + + let addLazyDiagnostic = (arg: () => void) => { + deferredDiagnosticsCallbacks.push(arg); + }; + // Cancellation that controls whether or not we can cancel in the middle of type checking. // In general cancelling is *not* safe for the type checker. We might be in the middle of // computing something, and we will leave our internals in an inconsistent state. Callers @@ -347,6 +354,7 @@ namespace ts { let instantiationDepth = 0; let inlineLevel = 0; let currentNode: Node | undefined; + let varianceTypeParameter: TypeParameter | undefined; const emptySymbols = createSymbolTable(); const arrayVariances = [VarianceFlags.Covariant]; @@ -704,8 +712,8 @@ namespace ts { // this call is done. cancellationToken = ct; - // Ensure file is type checked - checkSourceFile(file); + // Ensure file is type checked, with _eager_ diagnostic production, so identifiers are registered as potentially unused + checkSourceFileWithEagerDiagnostics(file); Debug.assert(!!(getNodeLinks(file).flags & NodeCheckFlags.TypeChecked)); diagnostics = addRange(diagnostics, suggestionDiagnostics.getDiagnostics(file.fileName)); @@ -761,6 +769,7 @@ namespace ts { const subtypeReductionCache = new Map(); const evolvingArrayTypes: EvolvingArrayType[] = []; const undefinedProperties: SymbolTable = new Map(); + const markerTypes = new Set(); const unknownSymbol = createSymbol(SymbolFlags.Property, "unknown" as __String); const resolvingSymbol = createSymbol(0, InternalSymbolName.Resolving); @@ -1781,6 +1790,11 @@ namespace ts { } } + function isConstAssertion(location: Node) { + return (isAssertionExpression(location) && isConstTypeReference(location.type)) + || (isJSDocTypeTag(location) && isConstTypeReference(location.typeExpression)); + } + /** * Resolve a given name for a given meaning at a given location. An error is reported if the name was not found and * the nameNotFoundMessage argument is not undefined. Returns the resolved symbol, or undefined if no symbol with @@ -1822,6 +1836,11 @@ namespace ts { let isInExternalModule = false; loop: while (location) { + if (name === "const" && isConstAssertion(location)) { + // `const` in an `as const` has no symbol, but issues no error because there is no *actual* lookup of the type + // (it refers to the constant type of the expression instead) + return undefined; + } // Locals of a source file are not in scope (because they get merged into the global symbol table) if (location.locals && !isGlobalSourceFile(location)) { if (result = lookup(location.locals, name, meaning)) { @@ -2140,121 +2159,125 @@ namespace ts { } } if (!result) { - if (nameNotFoundMessage && produceDiagnostics) { - if (!errorLocation || - !checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg!) && // TODO: GH#18217 - !checkAndReportErrorForExtendingInterface(errorLocation) && - !checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) && - !checkAndReportErrorForExportingPrimitiveType(errorLocation, name) && - !checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) && - !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) && - !checkAndReportErrorForUsingValueAsType(errorLocation, name, meaning)) { - let suggestion: Symbol | undefined; - if (getSpellingSuggestions && suggestionCount < maximumSuggestionCount) { - suggestion = getSuggestedSymbolForNonexistentSymbol(originalLocation, name, meaning); - const isGlobalScopeAugmentationDeclaration = suggestion?.valueDeclaration && isAmbientModule(suggestion.valueDeclaration) && isGlobalScopeAugmentation(suggestion.valueDeclaration); - if (isGlobalScopeAugmentationDeclaration) { - suggestion = undefined; - } - if (suggestion) { - const suggestionName = symbolToString(suggestion); - const isUncheckedJS = isUncheckedJSSuggestion(originalLocation, suggestion, /*excludeClasses*/ false); - const message = meaning === SymbolFlags.Namespace || nameArg && typeof nameArg !== "string" && nodeIsSynthesized(nameArg) ? Diagnostics.Cannot_find_namespace_0_Did_you_mean_1 - : isUncheckedJS ? Diagnostics.Could_not_find_name_0_Did_you_mean_1 - : Diagnostics.Cannot_find_name_0_Did_you_mean_1; - const diagnostic = createError(errorLocation, message, diagnosticName(nameArg!), suggestionName); - addErrorOrSuggestion(!isUncheckedJS, diagnostic); - if (suggestion.valueDeclaration) { - addRelatedInfo( - diagnostic, - createDiagnosticForNode(suggestion.valueDeclaration, Diagnostics._0_is_declared_here, suggestionName) - ); + if (nameNotFoundMessage) { + addLazyDiagnostic(() => { + if (!errorLocation || + !checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg!) && // TODO: GH#18217 + !checkAndReportErrorForExtendingInterface(errorLocation) && + !checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) && + !checkAndReportErrorForExportingPrimitiveType(errorLocation, name) && + !checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) && + !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) && + !checkAndReportErrorForUsingValueAsType(errorLocation, name, meaning)) { + let suggestion: Symbol | undefined; + if (getSpellingSuggestions && suggestionCount < maximumSuggestionCount) { + suggestion = getSuggestedSymbolForNonexistentSymbol(originalLocation, name, meaning); + const isGlobalScopeAugmentationDeclaration = suggestion?.valueDeclaration && isAmbientModule(suggestion.valueDeclaration) && isGlobalScopeAugmentation(suggestion.valueDeclaration); + if (isGlobalScopeAugmentationDeclaration) { + suggestion = undefined; + } + if (suggestion) { + const suggestionName = symbolToString(suggestion); + const isUncheckedJS = isUncheckedJSSuggestion(originalLocation, suggestion, /*excludeClasses*/ false); + const message = meaning === SymbolFlags.Namespace || nameArg && typeof nameArg !== "string" && nodeIsSynthesized(nameArg) ? Diagnostics.Cannot_find_namespace_0_Did_you_mean_1 + : isUncheckedJS ? Diagnostics.Could_not_find_name_0_Did_you_mean_1 + : Diagnostics.Cannot_find_name_0_Did_you_mean_1; + const diagnostic = createError(errorLocation, message, diagnosticName(nameArg!), suggestionName); + addErrorOrSuggestion(!isUncheckedJS, diagnostic); + if (suggestion.valueDeclaration) { + addRelatedInfo( + diagnostic, + createDiagnosticForNode(suggestion.valueDeclaration, Diagnostics._0_is_declared_here, suggestionName) + ); + } } } + if (!suggestion) { + if (nameArg) { + const lib = getSuggestedLibForNonExistentName(nameArg); + if (lib) { + error(errorLocation, nameNotFoundMessage, diagnosticName(nameArg), lib); + } + else { + error(errorLocation, nameNotFoundMessage, diagnosticName(nameArg)); + } + } + } + suggestionCount++; } - if (!suggestion) { - if (nameArg) { - const lib = getSuggestedLibForNonExistentName(nameArg); - if (lib) { - error(errorLocation, nameNotFoundMessage, diagnosticName(nameArg), lib); - } - else { - error(errorLocation, nameNotFoundMessage, diagnosticName(nameArg)); - } - } - } - suggestionCount++; - } + }); } return undefined; } + if (propertyWithInvalidInitializer && !(getEmitScriptTarget(compilerOptions) === ScriptTarget.ESNext && useDefineForClassFields)) { + // We have a match, but the reference occurred within a property initializer and the identifier also binds + // to a local variable in the constructor where the code will be emitted. Note that this is actually allowed + // with ESNext+useDefineForClassFields because the scope semantics are different. + const propertyName = (propertyWithInvalidInitializer as PropertyDeclaration).name; + error(errorLocation, Diagnostics.Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor, + declarationNameToString(propertyName), diagnosticName(nameArg!)); + return undefined; + } + // Perform extra checks only if error reporting was requested - if (nameNotFoundMessage && produceDiagnostics) { - if (propertyWithInvalidInitializer && !(getEmitScriptTarget(compilerOptions) === ScriptTarget.ESNext && useDefineForClassFields)) { - // We have a match, but the reference occurred within a property initializer and the identifier also binds - // to a local variable in the constructor where the code will be emitted. Note that this is actually allowed - // with ESNext+useDefineForClassFields because the scope semantics are different. - const propertyName = (propertyWithInvalidInitializer as PropertyDeclaration).name; - error(errorLocation, Diagnostics.Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor, - declarationNameToString(propertyName), diagnosticName(nameArg!)); - return undefined; - } + if (nameNotFoundMessage) { + addLazyDiagnostic(() => { + // Only check for block-scoped variable if we have an error location and are looking for the + // name with variable meaning + // For example, + // declare module foo { + // interface bar {} + // } + // const foo/*1*/: foo/*2*/.bar; + // The foo at /*1*/ and /*2*/ will share same symbol with two meanings: + // block-scoped variable and namespace module. However, only when we + // try to resolve name in /*1*/ which is used in variable position, + // we want to check for block-scoped + if (errorLocation && + (meaning & SymbolFlags.BlockScopedVariable || + ((meaning & SymbolFlags.Class || meaning & SymbolFlags.Enum) && (meaning & SymbolFlags.Value) === SymbolFlags.Value))) { + const exportOrLocalSymbol = getExportSymbolOfValueSymbolIfExported(result!); + if (exportOrLocalSymbol.flags & SymbolFlags.BlockScopedVariable || exportOrLocalSymbol.flags & SymbolFlags.Class || exportOrLocalSymbol.flags & SymbolFlags.Enum) { + checkResolvedBlockScopedVariable(exportOrLocalSymbol, errorLocation); + } + } - // Only check for block-scoped variable if we have an error location and are looking for the - // name with variable meaning - // For example, - // declare module foo { - // interface bar {} - // } - // const foo/*1*/: foo/*2*/.bar; - // The foo at /*1*/ and /*2*/ will share same symbol with two meanings: - // block-scoped variable and namespace module. However, only when we - // try to resolve name in /*1*/ which is used in variable position, - // we want to check for block-scoped - if (errorLocation && - (meaning & SymbolFlags.BlockScopedVariable || - ((meaning & SymbolFlags.Class || meaning & SymbolFlags.Enum) && (meaning & SymbolFlags.Value) === SymbolFlags.Value))) { - const exportOrLocalSymbol = getExportSymbolOfValueSymbolIfExported(result); - if (exportOrLocalSymbol.flags & SymbolFlags.BlockScopedVariable || exportOrLocalSymbol.flags & SymbolFlags.Class || exportOrLocalSymbol.flags & SymbolFlags.Enum) { - checkResolvedBlockScopedVariable(exportOrLocalSymbol, errorLocation); + // If we're in an external module, we can't reference value symbols created from UMD export declarations + if (result && isInExternalModule && (meaning & SymbolFlags.Value) === SymbolFlags.Value && !(originalLocation!.flags & NodeFlags.JSDoc)) { + const merged = getMergedSymbol(result); + if (length(merged.declarations) && every(merged.declarations, d => isNamespaceExportDeclaration(d) || isSourceFile(d) && !!d.symbol.globalExports)) { + errorOrSuggestion(!compilerOptions.allowUmdGlobalAccess, errorLocation!, Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, unescapeLeadingUnderscores(name)); + } } - } - // If we're in an external module, we can't reference value symbols created from UMD export declarations - if (result && isInExternalModule && (meaning & SymbolFlags.Value) === SymbolFlags.Value && !(originalLocation!.flags & NodeFlags.JSDoc)) { - const merged = getMergedSymbol(result); - if (length(merged.declarations) && every(merged.declarations, d => isNamespaceExportDeclaration(d) || isSourceFile(d) && !!d.symbol.globalExports)) { - errorOrSuggestion(!compilerOptions.allowUmdGlobalAccess, errorLocation!, Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, unescapeLeadingUnderscores(name)); + // If we're in a parameter initializer or binding name, we can't reference the values of the parameter whose initializer we're within or parameters to the right + if (result && associatedDeclarationForContainingInitializerOrBindingName && !withinDeferredContext && (meaning & SymbolFlags.Value) === SymbolFlags.Value) { + const candidate = getMergedSymbol(getLateBoundSymbol(result)); + const root = (getRootDeclaration(associatedDeclarationForContainingInitializerOrBindingName) as ParameterDeclaration); + // A parameter initializer or binding pattern initializer within a parameter cannot refer to itself + if (candidate === getSymbolOfNode(associatedDeclarationForContainingInitializerOrBindingName)) { + error(errorLocation, Diagnostics.Parameter_0_cannot_reference_itself, declarationNameToString(associatedDeclarationForContainingInitializerOrBindingName.name)); + } + // And it cannot refer to any declarations which come after it + else if (candidate.valueDeclaration && candidate.valueDeclaration.pos > associatedDeclarationForContainingInitializerOrBindingName.pos && root.parent.locals && lookup(root.parent.locals, candidate.escapedName, meaning) === candidate) { + error(errorLocation, Diagnostics.Parameter_0_cannot_reference_identifier_1_declared_after_it, declarationNameToString(associatedDeclarationForContainingInitializerOrBindingName.name), declarationNameToString(errorLocation as Identifier)); + } } - } - - // If we're in a parameter initializer or binding name, we can't reference the values of the parameter whose initializer we're within or parameters to the right - if (result && associatedDeclarationForContainingInitializerOrBindingName && !withinDeferredContext && (meaning & SymbolFlags.Value) === SymbolFlags.Value) { - const candidate = getMergedSymbol(getLateBoundSymbol(result)); - const root = (getRootDeclaration(associatedDeclarationForContainingInitializerOrBindingName) as ParameterDeclaration); - // A parameter initializer or binding pattern initializer within a parameter cannot refer to itself - if (candidate === getSymbolOfNode(associatedDeclarationForContainingInitializerOrBindingName)) { - error(errorLocation, Diagnostics.Parameter_0_cannot_reference_itself, declarationNameToString(associatedDeclarationForContainingInitializerOrBindingName.name)); + if (result && errorLocation && meaning & SymbolFlags.Value && result.flags & SymbolFlags.Alias && !(result.flags & SymbolFlags.Value) && !isValidTypeOnlyAliasUseSite(errorLocation)) { + const typeOnlyDeclaration = getTypeOnlyAliasDeclaration(result); + if (typeOnlyDeclaration) { + const message = typeOnlyDeclaration.kind === SyntaxKind.ExportSpecifier + ? Diagnostics._0_cannot_be_used_as_a_value_because_it_was_exported_using_export_type + : Diagnostics._0_cannot_be_used_as_a_value_because_it_was_imported_using_import_type; + const unescapedName = unescapeLeadingUnderscores(name); + addTypeOnlyDeclarationRelatedInfo( + error(errorLocation, message, unescapedName), + typeOnlyDeclaration, + unescapedName); + } } - // And it cannot refer to any declarations which come after it - else if (candidate.valueDeclaration && candidate.valueDeclaration.pos > associatedDeclarationForContainingInitializerOrBindingName.pos && root.parent.locals && lookup(root.parent.locals, candidate.escapedName, meaning) === candidate) { - error(errorLocation, Diagnostics.Parameter_0_cannot_reference_identifier_1_declared_after_it, declarationNameToString(associatedDeclarationForContainingInitializerOrBindingName.name), declarationNameToString(errorLocation as Identifier)); - } - } - if (result && errorLocation && meaning & SymbolFlags.Value && result.flags & SymbolFlags.Alias && !(result.flags & SymbolFlags.Value) && !isValidTypeOnlyAliasUseSite(errorLocation)) { - const typeOnlyDeclaration = getTypeOnlyAliasDeclaration(result); - if (typeOnlyDeclaration) { - const message = typeOnlyDeclaration.kind === SyntaxKind.ExportSpecifier - ? Diagnostics._0_cannot_be_used_as_a_value_because_it_was_exported_using_export_type - : Diagnostics._0_cannot_be_used_as_a_value_because_it_was_imported_using_import_type; - const unescapedName = unescapeLeadingUnderscores(name); - addTypeOnlyDeclarationRelatedInfo( - error(errorLocation, message, unescapedName), - typeOnlyDeclaration, - unescapedName); - } - } + }); } return result; } @@ -4093,9 +4116,7 @@ namespace ts { const result = new Type(checker, flags); typeCount++; result.id = typeCount; - if (produceDiagnostics) { // Only record types from one checker - tracing?.recordType(result); - } + tracing?.recordType(result); return result; } @@ -4985,9 +5006,12 @@ namespace ts { return factory.createTypeReferenceNode(factory.createIdentifier(idText(name)), /*typeArguments*/ undefined); } // Ignore constraint/default when creating a usage (as opposed to declaration) of a type parameter. - return type.symbol - ? symbolToTypeNode(type.symbol, context, SymbolFlags.Type) - : factory.createTypeReferenceNode(factory.createIdentifier("?"), /*typeArguments*/ undefined); + if (type.symbol) { + return symbolToTypeNode(type.symbol, context, SymbolFlags.Type); + } + const name = (type === markerSuperType || type === markerSubType) && varianceTypeParameter && varianceTypeParameter.symbol ? + (type === markerSubType ? "sub-" : "super-") + symbolName(varianceTypeParameter.symbol) : "?"; + return factory.createTypeReferenceNode(factory.createIdentifier(name), /*typeArguments*/ undefined); } if (type.flags & TypeFlags.Union && (type as UnionType).origin) { type = (type as UnionType).origin!; @@ -5107,7 +5131,7 @@ namespace ts { // type stays homomorphic return factory.createConditionalTypeNode( typeToTypeNodeHelper(getModifiersTypeFromMappedType(type), context), - factory.createInferTypeNode(factory.createTypeParameterDeclaration(factory.cloneNode(newTypeVariable!.typeName) as Identifier)), + factory.createInferTypeNode(factory.createTypeParameterDeclaration(/*modifiers*/ undefined, factory.cloneNode(newTypeVariable!.typeName) as Identifier)), result, factory.createKeywordTypeNode(SyntaxKind.NeverKeyword) ); @@ -5795,11 +5819,12 @@ namespace ts { function typeParameterToDeclarationWithConstraint(type: TypeParameter, context: NodeBuilderContext, constraintNode: TypeNode | undefined): TypeParameterDeclaration { const savedContextFlags = context.flags; context.flags &= ~NodeBuilderFlags.WriteTypeParametersInQualifiedName; // Avoids potential infinite loop when building for a claimspace with a generic + const modifiers = factory.createModifiersFromModifierFlags(getVarianceModifiers(type)); const name = typeParameterToName(type, context); const defaultParameter = getDefaultFromTypeParameter(type); const defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context); context.flags = savedContextFlags; - return factory.createTypeParameterDeclaration(name, constraintNode, defaultParameterNode); + return factory.createTypeParameterDeclaration(modifiers, name, constraintNode, defaultParameterNode); } function typeParameterToDeclaration(type: TypeParameter, context: NodeBuilderContext, constraint = getConstraintOfTypeParameter(type)): TypeParameterDeclaration { @@ -8505,6 +8530,8 @@ namespace ts { return !!(target as TypeReference).resolvedTypeArguments; case TypeSystemPropertyName.ResolvedBaseTypes: return !!(target as InterfaceType).baseTypesResolved; + case TypeSystemPropertyName.WriteType: + return !!getSymbolLinks(target as Symbol).writeType; } return Debug.assertNever(propertyName); } @@ -9488,6 +9515,11 @@ namespace ts { } return getWidenedType(getWidenedLiteralType(checkExpression(declaration.statements[0].expression))); } + if (isAccessor(declaration)) { + // Binding of certain patterns in JS code will occasionally mark symbols as both properties + // and accessors. Here we dispatch to accessor resolution if needed. + return getTypeOfAccessors(symbol); + } // Handle variable, parameter or property if (!pushTypeResolution(symbol, TypeSystemPropertyName.Type)) { @@ -9553,9 +9585,6 @@ namespace ts { else if (isEnumMember(declaration)) { type = getTypeOfEnumMember(symbol); } - else if (isAccessor(declaration)) { - type = resolveTypeOfAccessors(symbol) || Debug.fail("Non-write accessor resolution must always produce a type"); - } else { return Debug.fail("Unhandled declaration kind! " + Debug.formatSyntaxKind(declaration.kind) + " for " + Debug.formatSymbol(symbol)); } @@ -9600,93 +9629,62 @@ namespace ts { function getTypeOfAccessors(symbol: Symbol): Type { const links = getSymbolLinks(symbol); - return links.type || (links.type = getTypeOfAccessorsWorker(symbol) || Debug.fail("Read type of accessor must always produce a type")); + if (!links.type) { + if (!pushTypeResolution(symbol, TypeSystemPropertyName.Type)) { + return errorType; + } + const getter = getDeclarationOfKind(symbol, SyntaxKind.GetAccessor); + const setter = getDeclarationOfKind(symbol, SyntaxKind.SetAccessor); + // We try to resolve a getter type annotation, a setter type annotation, or a getter function + // body return type inference, in that order. + let type = getter && isInJSFile(getter) && getTypeForDeclarationFromJSDocComment(getter) || + getAnnotatedAccessorType(getter) || + getAnnotatedAccessorType(setter) || + getter && getter.body && getReturnTypeFromBody(getter); + if (!type) { + if (setter && !isPrivateWithinAmbient(setter)) { + errorOrSuggestion(noImplicitAny, setter, Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol)); + } + else if (getter && !isPrivateWithinAmbient(getter)) { + errorOrSuggestion(noImplicitAny, getter, Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); + } + type = anyType; + } + if (!popTypeResolution()) { + if (getAnnotatedAccessorTypeNode(getter)) { + error(getter, Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol)); + } + else if (getAnnotatedAccessorTypeNode(setter)) { + error(setter, Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol)); + } + else if (getter && noImplicitAny) { + error(getter, Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, symbolToString(symbol)); + } + type = anyType; + } + links.type = type; + } + return links.type; } - function getTypeOfSetAccessor(symbol: Symbol): Type | undefined { + function getWriteTypeOfAccessors(symbol: Symbol): Type { const links = getSymbolLinks(symbol); - return links.writeType || (links.writeType = getTypeOfAccessorsWorker(symbol, /*writing*/ true)); - } - - function getTypeOfAccessorsWorker(symbol: Symbol, writing = false): Type | undefined { - if (!pushTypeResolution(symbol, TypeSystemPropertyName.Type)) { - return errorType; - } - - let type = resolveTypeOfAccessors(symbol, writing); - - if (!popTypeResolution()) { - type = anyType; - if (noImplicitAny) { - const getter = getDeclarationOfKind(symbol, SyntaxKind.GetAccessor); - error(getter, Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, symbolToString(symbol)); + if (!links.writeType) { + if (!pushTypeResolution(symbol, TypeSystemPropertyName.WriteType)) { + return errorType; } - } - return type; - } - - function resolveTypeOfAccessors(symbol: Symbol, writing = false) { - const getter = getDeclarationOfKind(symbol, SyntaxKind.GetAccessor); - const setter = getDeclarationOfKind(symbol, SyntaxKind.SetAccessor); - - // For write operations, prioritize type annotations on the setter - if (writing) { - const setterType = getAnnotatedAccessorType(setter); - if (setterType) { - return instantiateTypeIfNeeded(setterType, symbol); + const setter = getDeclarationOfKind(symbol, SyntaxKind.SetAccessor); + let writeType = getAnnotatedAccessorType(setter); + if (!popTypeResolution()) { + if (getAnnotatedAccessorTypeNode(setter)) { + error(setter, Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol)); + } + writeType = anyType; } + // Absent an explicit setter type annotation we use the read type of the accessor. + links.writeType = writeType || getTypeOfAccessors(symbol); } - // Else defer to the getter type - - if (getter && isInJSFile(getter)) { - const jsDocType = getTypeForDeclarationFromJSDocComment(getter); - if (jsDocType) { - return instantiateTypeIfNeeded(jsDocType, symbol); - } - } - - // Try to see if the user specified a return type on the get-accessor. - const getterType = getAnnotatedAccessorType(getter); - if (getterType) { - return instantiateTypeIfNeeded(getterType, symbol); - } - - // If the user didn't specify a return type, try to use the set-accessor's parameter type. - const setterType = getAnnotatedAccessorType(setter); - if (setterType) { - return setterType; - } - - // If there are no specified types, try to infer it from the body of the get accessor if it exists. - if (getter && getter.body) { - const returnTypeFromBody = getReturnTypeFromBody(getter); - return instantiateTypeIfNeeded(returnTypeFromBody, symbol); - } - - // Otherwise, fall back to 'any'. - if (setter) { - if (!isPrivateWithinAmbient(setter)) { - errorOrSuggestion(noImplicitAny, setter, Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol)); - } - return anyType; - } - else if (getter) { - Debug.assert(!!getter, "there must exist a getter as we are current checking either setter or getter in this function"); - if (!isPrivateWithinAmbient(getter)) { - errorOrSuggestion(noImplicitAny, getter, Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); - } - return anyType; - } - return undefined; - - function instantiateTypeIfNeeded(type: Type, symbol: Symbol) { - if (getCheckFlags(symbol) & CheckFlags.Instantiated) { - const links = getSymbolLinks(symbol); - return instantiateType(type, links.mapper); - } - - return type; - } + return links.writeType; } function getBaseTypeVariableOfClass(symbol: Symbol) { @@ -9774,17 +9772,12 @@ namespace ts { function getTypeOfInstantiatedSymbol(symbol: Symbol): Type { const links = getSymbolLinks(symbol); - if (!links.type) { - if (!pushTypeResolution(symbol, TypeSystemPropertyName.Type)) { - return links.type = errorType; - } - let type = instantiateType(getTypeOfSymbol(links.target!), links.mapper); - if (!popTypeResolution()) { - type = reportCircularityError(symbol); - } - links.type = type; - } - return links.type; + return links.type || (links.type = instantiateType(getTypeOfSymbol(links.target!), links.mapper)); + } + + function getWriteTypeOfInstantiatedSymbol(symbol: Symbol): Type { + const links = getSymbolLinks(symbol); + return links.writeType || (links.writeType = instantiateType(getWriteTypeOfSymbol(links.target!), links.mapper)); } function reportCircularityError(symbol: Symbol) { @@ -9827,36 +9820,23 @@ namespace ts { } /** - * Distinct write types come only from set accessors, but union and intersection - * properties deriving from set accessors will either pre-compute or defer the - * union or intersection of the writeTypes of their constituents. To account for - * this, we will assume that any deferred type or transient symbol may have a - * `writeType` (or a deferred write type ready to be computed) that should be - * used before looking for set accessor declarations. + * Distinct write types come only from set accessors, but synthetic union and intersection + * properties deriving from set accessors will either pre-compute or defer the union or + * intersection of the writeTypes of their constituents. */ function getWriteTypeOfSymbol(symbol: Symbol): Type { const checkFlags = getCheckFlags(symbol); - if (checkFlags & CheckFlags.DeferredType) { - const writeType = getWriteTypeOfSymbolWithDeferredType(symbol); - if (writeType) { - return writeType; - } + if (symbol.flags & SymbolFlags.Property) { + return checkFlags & CheckFlags.SyntheticProperty ? + checkFlags & CheckFlags.DeferredType ? + getWriteTypeOfSymbolWithDeferredType(symbol) || getTypeOfSymbolWithDeferredType(symbol) : + (symbol as TransientSymbol).writeType || (symbol as TransientSymbol).type! : + getTypeOfSymbol(symbol); } - if (symbol.flags & SymbolFlags.Transient) { - const { writeType } = symbol as TransientSymbol; - if (writeType) { - return writeType; - } - } - return getSetAccessorTypeOfSymbol(symbol); - } - - function getSetAccessorTypeOfSymbol(symbol: Symbol): Type { if (symbol.flags & SymbolFlags.Accessor) { - const type = getTypeOfSetAccessor(symbol); - if (type) { - return type; - } + return checkFlags & CheckFlags.Instantiated ? + getWriteTypeOfInstantiatedSymbol(symbol) : + getWriteTypeOfAccessors(symbol); } return getTypeOfSymbol(symbol); } @@ -12862,7 +12842,19 @@ namespace ts { p.typeExpression && isJSDocVariadicType(p.typeExpression.type) ? p.typeExpression.type : undefined); const syntheticArgsSymbol = createSymbol(SymbolFlags.Variable, "args" as __String, CheckFlags.RestParameter); - syntheticArgsSymbol.type = lastParamVariadicType ? createArrayType(getTypeFromTypeNode(lastParamVariadicType.type)) : anyArrayType; + if (lastParamVariadicType) { + // Parameter has effective annotation, lock in type + syntheticArgsSymbol.type = createArrayType(getTypeFromTypeNode(lastParamVariadicType.type)); + } + else { + // Parameter has no annotation + // By using a `DeferredType` symbol, we allow the type of this rest arg to be overriden by contextual type assignment so long as its type hasn't been + // cached by `getTypeOfSymbol` yet. + syntheticArgsSymbol.checkFlags |= CheckFlags.DeferredType; + syntheticArgsSymbol.deferralParent = neverType; + syntheticArgsSymbol.deferralConstituents = [anyArrayType]; + syntheticArgsSymbol.deferralWriteConstituents = [anyArrayType]; + } if (lastParamVariadicType) { // Replace the last parameter with a rest parameter. parameters.pop(); @@ -15238,24 +15230,32 @@ namespace ts { } return type; - function addSpans(texts: readonly string[], types: readonly Type[]): boolean { + function addSpans(texts: readonly string[] | string, types: readonly Type[]): boolean { + const isTextsArray = isArray(texts); for (let i = 0; i < types.length; i++) { const t = types[i]; + const addText = isTextsArray ? texts[i + 1] : texts; if (t.flags & (TypeFlags.Literal | TypeFlags.Null | TypeFlags.Undefined)) { text += getTemplateStringForType(t) || ""; - text += texts[i + 1]; + text += addText; + if (!isTextsArray) return true; } else if (t.flags & TypeFlags.TemplateLiteral) { text += (t as TemplateLiteralType).texts[0]; if (!addSpans((t as TemplateLiteralType).texts, (t as TemplateLiteralType).types)) return false; - text += texts[i + 1]; + text += addText; + if (!isTextsArray) return true; } else if (isGenericIndexType(t) || isPatternLiteralPlaceholderType(t)) { newTypes.push(t); newTexts.push(text); - text = texts[i + 1]; + text = addText; } - else { + else if (t.flags & TypeFlags.Intersection) { + const added = addSpans(texts[i + 1], (t as IntersectionType).types); + if (!added) return false; + } + else if (isTextsArray) { return false; } } @@ -18392,7 +18392,7 @@ namespace ts { generalizedSourceType = getTypeNameForErrorDisplay(generalizedSource); } - if (target.flags & TypeFlags.TypeParameter) { + if (target.flags & TypeFlags.TypeParameter && target !== markerSuperType && target !== markerSubType) { const constraint = getBaseConstraintOfType(target); let needsOriginalSource; if (constraint && (isTypeAssignableTo(generalizedSource, constraint) || (needsOriginalSource = isTypeAssignableTo(source, constraint)))) { @@ -18668,6 +18668,9 @@ namespace ts { return; } reportRelationError(headMessage, source, target); + if (strictNullChecks && source.flags & TypeFlags.TypeVariable && source.symbol?.declarations?.[0] && !getConstraintOfType(source as TypeVariable) && isRelatedTo(emptyObjectType, extractTypesOfKind(target, ~TypeFlags.NonPrimitive))) { + associateRelatedInfo(createDiagnosticForNode(source.symbol.declarations[0], Diagnostics.This_type_parameter_probably_needs_an_extends_object_constraint)); + } } function traceUnionsOrIntersectionsTooLarge(source: Type, target: Type): void { @@ -19215,9 +19218,8 @@ namespace ts { // We limit alias variance probing to only object and conditional types since their alias behavior // is more predictable than other, interned types, which may or may not have an alias depending on // the order in which things were checked. - if (sourceFlags & (TypeFlags.Object | TypeFlags.Conditional) && source.aliasSymbol && - source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol && - !(source.aliasTypeArgumentsContainsMarker || target.aliasTypeArgumentsContainsMarker)) { + if (sourceFlags & (TypeFlags.Object | TypeFlags.Conditional) && source.aliasSymbol && source.aliasTypeArguments && + source.aliasSymbol === target.aliasSymbol && !(isMarkerType(source) || isMarkerType(target))) { const variances = getAliasVariances(source.aliasSymbol); if (variances === emptyArray) { return Ternary.Unknown; @@ -19459,7 +19461,7 @@ namespace ts { // IndexedAccess comparisons are handled above in the `targetFlags & TypeFlage.IndexedAccess` branch if (!(sourceFlags & TypeFlags.IndexedAccess && targetFlags & TypeFlags.IndexedAccess)) { const constraint = getConstraintOfType(source as TypeVariable); - if (!constraint || (sourceFlags & TypeFlags.TypeParameter && constraint.flags & TypeFlags.Any)) { + if (!strictNullChecks && (!constraint || (sourceFlags & TypeFlags.TypeParameter && constraint.flags & TypeFlags.Any))) { // A type variable with no constraint is not related to the non-primitive object type. if (result = isRelatedTo(emptyObjectType, extractTypesOfKind(target, ~TypeFlags.NonPrimitive), RecursionFlags.Both)) { resetErrorInfo(saveErrorInfo); @@ -19467,12 +19469,12 @@ namespace ts { } } // hi-speed no-this-instantiation check (less accurate, but avoids costly `this`-instantiation when the constraint will suffice), see #28231 for report on why this is needed - else if (result = isRelatedTo(constraint, target, RecursionFlags.Source, /*reportErrors*/ false, /*headMessage*/ undefined, intersectionState)) { + else if (constraint && (result = isRelatedTo(constraint, target, RecursionFlags.Source, /*reportErrors*/ false, /*headMessage*/ undefined, intersectionState))) { resetErrorInfo(saveErrorInfo); return result; } // slower, fuller, this-instantiated check (necessary when comparing raw `this` types from base classes), see `subclassWithPolymorphicThisIsAssignable.ts` test for example - else if (result = isRelatedTo(getTypeWithThisArgument(constraint, source), target, RecursionFlags.Source, reportErrors && !(targetFlags & sourceFlags & TypeFlags.TypeParameter), /*headMessage*/ undefined, intersectionState)) { + else if (constraint && (result = isRelatedTo(getTypeWithThisArgument(constraint, source), target, RecursionFlags.Source, reportErrors && !(targetFlags & sourceFlags & TypeFlags.TypeParameter), /*headMessage*/ undefined, intersectionState))) { resetErrorInfo(saveErrorInfo); return result; } @@ -19596,7 +19598,7 @@ namespace ts { return Ternary.False; } if (getObjectFlags(source) & ObjectFlags.Reference && getObjectFlags(target) & ObjectFlags.Reference && (source as TypeReference).target === (target as TypeReference).target && - !isTupleType(source) && !(getObjectFlags(source) & ObjectFlags.MarkerType || getObjectFlags(target) & ObjectFlags.MarkerType)) { + !isTupleType(source) && !(isMarkerType(source) || isMarkerType(target))) { // When strictNullChecks is disabled, the element type of the empty array literal is undefinedWideningType, // and an empty array literal wouldn't be assignable to a `never[]` without this check. if (isEmptyArrayLiteralType(source)) { @@ -20547,21 +20549,15 @@ namespace ts { return false; } - // Return a type reference where the source type parameter is replaced with the target marker - // type, and flag the result as a marker type reference. - function getMarkerTypeReference(type: GenericType, source: TypeParameter, target: Type) { - const result = createTypeReference(type, map(type.typeParameters, t => t === source ? target : t)); - result.objectFlags |= ObjectFlags.MarkerType; - return result; + function getVariances(type: GenericType): VarianceFlags[] { + // Arrays and tuples are known to be covariant, no need to spend time computing this. + return type === globalArrayType || type === globalReadonlyArrayType || type.objectFlags & ObjectFlags.Tuple ? + arrayVariances : + getVariancesWorker(type.symbol, type.typeParameters); } function getAliasVariances(symbol: Symbol) { - const links = getSymbolLinks(symbol); - return getVariancesWorker(links.typeParameters, links, (_links, param, marker) => { - const type = getTypeAliasInstantiation(symbol, instantiateTypes(links.typeParameters!, makeUnaryTypeMapper(param, marker))); - type.aliasTypeArgumentsContainsMarker = true; - return type; - }); + return getVariancesWorker(symbol, getSymbolLinks(symbol).typeParameters); } // Return an array containing the variance of each type parameter. The variance is effectively @@ -20569,55 +20565,71 @@ namespace ts { // generic type are structurally compared. We infer the variance information by comparing // instantiations of the generic type for type arguments with known relations. The function // returns the emptyArray singleton when invoked recursively for the given generic type. - function getVariancesWorker(typeParameters: readonly TypeParameter[] = emptyArray, cache: TCache, createMarkerType: (input: TCache, param: TypeParameter, marker: Type) => Type): VarianceFlags[] { - let variances = cache.variances; - if (!variances) { - tracing?.push(tracing.Phase.CheckTypes, "getVariancesWorker", { arity: typeParameters.length, id: (cache as any).id ?? (cache as any).declaredType?.id ?? -1 }); - // The emptyArray singleton is used to signal a recursive invocation. - cache.variances = emptyArray; - variances = []; + function getVariancesWorker(symbol: Symbol, typeParameters: readonly TypeParameter[] = emptyArray): VarianceFlags[] { + const links = getSymbolLinks(symbol); + if (!links.variances) { + tracing?.push(tracing.Phase.CheckTypes, "getVariancesWorker", { arity: typeParameters.length, id: getTypeId(getDeclaredTypeOfSymbol(symbol)) }); + links.variances = emptyArray; + const variances = []; for (const tp of typeParameters) { - let unmeasurable = false; - let unreliable = false; - const oldHandler = outofbandVarianceMarkerHandler; - outofbandVarianceMarkerHandler = (onlyUnreliable) => onlyUnreliable ? unreliable = true : unmeasurable = true; - // We first compare instantiations where the type parameter is replaced with - // marker types that have a known subtype relationship. From this we can infer - // invariance, covariance, contravariance or bivariance. - const typeWithSuper = createMarkerType(cache, tp, markerSuperType); - const typeWithSub = createMarkerType(cache, tp, markerSubType); - let variance = (isTypeAssignableTo(typeWithSub, typeWithSuper) ? VarianceFlags.Covariant : 0) | - (isTypeAssignableTo(typeWithSuper, typeWithSub) ? VarianceFlags.Contravariant : 0); - // If the instantiations appear to be related bivariantly it may be because the - // type parameter is independent (i.e. it isn't witnessed anywhere in the generic - // type). To determine this we compare instantiations where the type parameter is - // replaced with marker types that are known to be unrelated. - if (variance === VarianceFlags.Bivariant && isTypeAssignableTo(createMarkerType(cache, tp, markerOtherType), typeWithSuper)) { - variance = VarianceFlags.Independent; - } - outofbandVarianceMarkerHandler = oldHandler; - if (unmeasurable || unreliable) { - if (unmeasurable) { - variance |= VarianceFlags.Unmeasurable; + const modifiers = getVarianceModifiers(tp); + let variance = modifiers & ModifierFlags.Out ? + modifiers & ModifierFlags.In ? VarianceFlags.Invariant : VarianceFlags.Covariant : + modifiers & ModifierFlags.In ? VarianceFlags.Contravariant : undefined; + if (variance === undefined) { + let unmeasurable = false; + let unreliable = false; + const oldHandler = outofbandVarianceMarkerHandler; + outofbandVarianceMarkerHandler = (onlyUnreliable) => onlyUnreliable ? unreliable = true : unmeasurable = true; + // We first compare instantiations where the type parameter is replaced with + // marker types that have a known subtype relationship. From this we can infer + // invariance, covariance, contravariance or bivariance. + const typeWithSuper = createMarkerType(symbol, tp, markerSuperType); + const typeWithSub = createMarkerType(symbol, tp, markerSubType); + variance = (isTypeAssignableTo(typeWithSub, typeWithSuper) ? VarianceFlags.Covariant : 0) | + (isTypeAssignableTo(typeWithSuper, typeWithSub) ? VarianceFlags.Contravariant : 0); + // If the instantiations appear to be related bivariantly it may be because the + // type parameter is independent (i.e. it isn't witnessed anywhere in the generic + // type). To determine this we compare instantiations where the type parameter is + // replaced with marker types that are known to be unrelated. + if (variance === VarianceFlags.Bivariant && isTypeAssignableTo(createMarkerType(symbol, tp, markerOtherType), typeWithSuper)) { + variance = VarianceFlags.Independent; } - if (unreliable) { - variance |= VarianceFlags.Unreliable; + outofbandVarianceMarkerHandler = oldHandler; + if (unmeasurable || unreliable) { + if (unmeasurable) { + variance |= VarianceFlags.Unmeasurable; + } + if (unreliable) { + variance |= VarianceFlags.Unreliable; + } } } variances.push(variance); } - cache.variances = variances; + links.variances = variances; tracing?.pop(); } - return variances; + return links.variances; } - function getVariances(type: GenericType): VarianceFlags[] { - // Arrays and tuples are known to be covariant, no need to spend time computing this. - if (type === globalArrayType || type === globalReadonlyArrayType || type.objectFlags & ObjectFlags.Tuple) { - return arrayVariances; - } - return getVariancesWorker(type.typeParameters, type, getMarkerTypeReference); + function createMarkerType(symbol: Symbol, source: TypeParameter, target: Type) { + const mapper = makeUnaryTypeMapper(source, target); + const type = getDeclaredTypeOfSymbol(symbol); + const result = symbol.flags & SymbolFlags.TypeAlias ? + getTypeAliasInstantiation(symbol, instantiateTypes(getSymbolLinks(symbol).typeParameters!, mapper)) : + createTypeReference(type as GenericType, instantiateTypes((type as GenericType).typeParameters, mapper)); + markerTypes.add(getTypeId(result)); + return result; + } + + function isMarkerType(type: Type) { + return markerTypes.has(getTypeId(type)); + } + + function getVarianceModifiers(tp: TypeParameter): ModifierFlags { + return (some(tp.symbol?.declarations, d => hasSyntacticModifier(d, ModifierFlags.In)) ? ModifierFlags.In : 0) | + (some(tp.symbol?.declarations, d => hasSyntacticModifier(d, ModifierFlags.Out)) ? ModifierFlags.Out: 0); } // Return true if the given type reference has a 'void' type argument for a covariant type parameter. @@ -21624,12 +21636,14 @@ namespace ts { } function reportErrorsFromWidening(declaration: Declaration, type: Type, wideningKind?: WideningKind) { - if (produceDiagnostics && noImplicitAny && getObjectFlags(type) & ObjectFlags.ContainsWideningType && (!wideningKind || !getContextualSignatureForFunctionLikeDeclaration(declaration as FunctionLikeDeclaration))) { - // Report implicit any error within type if possible, otherwise report error on declaration - if (!reportWideningErrorsInType(type)) { - reportImplicitAny(declaration, type, wideningKind); + addLazyDiagnostic(() => { + if (noImplicitAny && getObjectFlags(type) & ObjectFlags.ContainsWideningType && (!wideningKind || !getContextualSignatureForFunctionLikeDeclaration(declaration as FunctionLikeDeclaration))) { + // Report implicit any error within type if possible, otherwise report error on declaration + if (!reportWideningErrorsInType(type)) { + reportImplicitAny(declaration, type, wideningKind); + } } - } + }); } function applyToParameterTypes(source: Signature, target: Signature, callback: (s: Type, t: Type) => void) { @@ -25185,7 +25199,7 @@ namespace ts { } } if (isDeclarationName(location) && isSetAccessor(location.parent) && getAnnotatedAccessorTypeNode(location.parent)) { - return resolveTypeOfAccessors(location.parent.symbol, /*writing*/ true)!; + return getWriteTypeOfAccessors(location.parent.symbol); } // The location isn't a reference to the given symbol, meaning we're being asked // a hypothetical question of what type the symbol would have if there was a reference @@ -26801,13 +26815,6 @@ namespace ts { return false; } - function uniqueStrings(strings: readonly __String[]): __String[] { - const unique = new Set(strings); - const result: __String[] = []; - unique.forEach(str => result.push(str)); - return result; - } - function discriminateContextualTypeByObjectMembers(node: ObjectLiteralExpression, contextualType: UnionType) { return getMatchingUnionConstituentForObjectLiteral(contextualType, node) || discriminateTypeByDiscriminableItems(contextualType, concatenate( @@ -26816,13 +26823,8 @@ namespace ts { prop => ([() => getContextFreeTypeOfExpression((prop as PropertyAssignment).initializer), prop.symbol.escapedName] as [() => Type, __String]) ), map( - uniqueStrings(flatMap(contextualType.types, memberType => - map( - filter(getPropertiesOfType(memberType), s => !!(s.flags & SymbolFlags.Optional) && !!node?.symbol?.members && !node.symbol.members.has(s.escapedName) && isDiscriminantProperty(contextualType, s.escapedName)), - s => s.escapedName - ) - )), - name => [() => undefinedType, name] as [() => Type, __String] + filter(getPropertiesOfType(contextualType), s => !!(s.flags & SymbolFlags.Optional) && !!node?.symbol?.members && !node.symbol.members.has(s.escapedName) && isDiscriminantProperty(contextualType, s.escapedName)), + s => [() => undefinedType, s.escapedName] as [() => Type, __String] ) ), isTypeAssignableTo, @@ -26838,13 +26840,8 @@ namespace ts { prop => ([!(prop as JsxAttribute).initializer ? (() => trueType) : (() => getContextFreeTypeOfExpression((prop as JsxAttribute).initializer!)), prop.symbol.escapedName] as [() => Type, __String]) ), map( - uniqueStrings(flatMap(contextualType.types, memberType => - map( - filter(getPropertiesOfType(memberType), s => !!(s.flags & SymbolFlags.Optional) && !!node?.symbol?.members && !node.symbol.members.has(s.escapedName) && isDiscriminantProperty(contextualType, s.escapedName)), - s => s.escapedName - ) - )), - name => [() => undefinedType, name] as [() => Type, __String] + filter(getPropertiesOfType(contextualType), s => !!(s.flags & SymbolFlags.Optional) && !!node?.symbol?.members && !node.symbol.members.has(s.escapedName) && isDiscriminantProperty(contextualType, s.escapedName)), + s => [() => undefinedType, s.escapedName] as [() => Type, __String] ) ), isTypeAssignableTo, @@ -28947,6 +28944,7 @@ namespace ts { && !isOptionalPropertyDeclaration(valueDeclaration) && !(isAccessExpression(node) && isAccessExpression(node.expression)) && !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right) + && !(isMethodDeclaration(valueDeclaration) && getCombinedModifierFlags(valueDeclaration) & ModifierFlags.Static) && (compilerOptions.useDefineForClassFields || !isPropertyDeclaredInAncestorClass(prop))) { diagnosticMessage = error(right, Diagnostics.Property_0_is_used_before_its_initialization, declarationName); } @@ -30307,7 +30305,7 @@ namespace ts { const isTaggedTemplate = node.kind === SyntaxKind.TaggedTemplateExpression; const isDecorator = node.kind === SyntaxKind.Decorator; const isJsxOpeningOrSelfClosingElement = isJsxOpeningLikeElement(node); - const reportErrors = !candidatesOutArray && produceDiagnostics; + const reportErrors = !candidatesOutArray; let typeArguments: NodeArray | undefined; @@ -31742,12 +31740,14 @@ namespace ts { checkSourceElement(type); exprType = getRegularTypeOfObjectLiteral(getBaseTypeOfLiteralType(exprType)); const targetType = getTypeFromTypeNode(type); - if (produceDiagnostics && !isErrorType(targetType)) { - const widenedType = getWidenedType(exprType); - if (!isTypeComparableTo(targetType, widenedType)) { - checkTypeComparableTo(exprType, targetType, errNode, - Diagnostics.Conversion_of_type_0_to_type_1_may_be_a_mistake_because_neither_type_sufficiently_overlaps_with_the_other_If_this_was_intentional_convert_the_expression_to_unknown_first); - } + if (!isErrorType(targetType)) { + addLazyDiagnostic(() => { + const widenedType = getWidenedType(exprType); + if (!isTypeComparableTo(targetType, widenedType)) { + checkTypeComparableTo(exprType, targetType, errNode, + Diagnostics.Conversion_of_type_0_to_type_1_may_be_a_mistake_because_neither_type_sufficiently_overlaps_with_the_other_If_this_was_intentional_convert_the_expression_to_unknown_first); + } + }); } return targetType; } @@ -32163,7 +32163,12 @@ namespace ts { if (signatureHasRestParameter(signature)) { // parameter might be a transient symbol generated by use of `arguments` in the function body. const parameter = last(signature.parameters); - if (isTransientSymbol(parameter) || !getEffectiveTypeAnnotationNode(parameter.valueDeclaration as ParameterDeclaration)) { + if (parameter.valueDeclaration + ? !getEffectiveTypeAnnotationNode(parameter.valueDeclaration as ParameterDeclaration) + // a declarationless parameter may still have a `.type` already set by its construction logic + // (which may pull a type from a jsdoc) - only allow fixing on `DeferredType` parameters with a fallback type + : !!(getCheckFlags(parameter) & CheckFlags.DeferredType) + ) { const contextualParameterType = getRestTypeAtPosition(context, len); assignParameterType(parameter, contextualParameterType); } @@ -32182,9 +32187,9 @@ namespace ts { function assignParameterType(parameter: Symbol, type?: Type) { const links = getSymbolLinks(parameter); if (!links.type) { - const declaration = parameter.valueDeclaration as ParameterDeclaration; - links.type = type || getWidenedTypeForVariableLikeDeclaration(declaration, /*reportErrors*/ true); - if (declaration.name.kind !== SyntaxKind.Identifier) { + const declaration = parameter.valueDeclaration as ParameterDeclaration | undefined; + links.type = type || (declaration ? getWidenedTypeForVariableLikeDeclaration(declaration, /*reportErrors*/ true) : getTypeOfSymbol(parameter)); + if (declaration && declaration.name.kind !== SyntaxKind.Identifier) { // if inference didn't come up with anything but unknown, fall back to the binding pattern if present. if (links.type === unknownType) { links.type = getTypeFromBindingPattern(declaration.name); @@ -32564,53 +32569,54 @@ namespace ts { * * @param returnType - return type of the function, can be undefined if return type is not explicitly specified */ - function checkAllCodePathsInNonVoidFunctionReturnOrThrow(func: FunctionLikeDeclaration | MethodSignature, returnType: Type | undefined): void { - if (!produceDiagnostics) { - return; - } + function checkAllCodePathsInNonVoidFunctionReturnOrThrow(func: FunctionLikeDeclaration | MethodSignature, returnType: Type | undefined) { + addLazyDiagnostic(checkAllCodePathsInNonVoidFunctionReturnOrThrowDiagnostics); + return; - const functionFlags = getFunctionFlags(func); - const type = returnType && unwrapReturnType(returnType, functionFlags); + function checkAllCodePathsInNonVoidFunctionReturnOrThrowDiagnostics(): void { + const functionFlags = getFunctionFlags(func); + const type = returnType && unwrapReturnType(returnType, functionFlags); - // Functions with with an explicitly specified 'void' or 'any' return type don't need any return expressions. - if (type && maybeTypeOfKind(type, TypeFlags.Any | TypeFlags.Void)) { - return; - } + // Functions with with an explicitly specified 'void' or 'any' return type don't need any return expressions. + if (type && maybeTypeOfKind(type, TypeFlags.Any | TypeFlags.Void)) { + return; + } - // If all we have is a function signature, or an arrow function with an expression body, then there is nothing to check. - // also if HasImplicitReturn flag is not set this means that all codepaths in function body end with return or throw - if (func.kind === SyntaxKind.MethodSignature || nodeIsMissing(func.body) || func.body!.kind !== SyntaxKind.Block || !functionHasImplicitReturn(func)) { - return; - } + // If all we have is a function signature, or an arrow function with an expression body, then there is nothing to check. + // also if HasImplicitReturn flag is not set this means that all codepaths in function body end with return or throw + if (func.kind === SyntaxKind.MethodSignature || nodeIsMissing(func.body) || func.body!.kind !== SyntaxKind.Block || !functionHasImplicitReturn(func)) { + return; + } - const hasExplicitReturn = func.flags & NodeFlags.HasExplicitReturn; - const errorNode = getEffectiveReturnTypeNode(func) || func; + const hasExplicitReturn = func.flags & NodeFlags.HasExplicitReturn; + const errorNode = getEffectiveReturnTypeNode(func) || func; - if (type && type.flags & TypeFlags.Never) { - error(errorNode, Diagnostics.A_function_returning_never_cannot_have_a_reachable_end_point); - } - else if (type && !hasExplicitReturn) { - // minimal check: function has syntactic return type annotation and no explicit return statements in the body - // this function does not conform to the specification. - error(errorNode, Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value); - } - else if (type && strictNullChecks && !isTypeAssignableTo(undefinedType, type)) { - error(errorNode, Diagnostics.Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined); - } - else if (compilerOptions.noImplicitReturns) { - if (!type) { - // If return type annotation is omitted check if function has any explicit return statements. - // If it does not have any - its inferred return type is void - don't do any checks. - // Otherwise get inferred return type from function body and report error only if it is not void / anytype - if (!hasExplicitReturn) { - return; + if (type && type.flags & TypeFlags.Never) { + error(errorNode, Diagnostics.A_function_returning_never_cannot_have_a_reachable_end_point); + } + else if (type && !hasExplicitReturn) { + // minimal check: function has syntactic return type annotation and no explicit return statements in the body + // this function does not conform to the specification. + error(errorNode, Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value); + } + else if (type && strictNullChecks && !isTypeAssignableTo(undefinedType, type)) { + error(errorNode, Diagnostics.Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined); + } + else if (compilerOptions.noImplicitReturns) { + if (!type) { + // If return type annotation is omitted check if function has any explicit return statements. + // If it does not have any - its inferred return type is void - don't do any checks. + // Otherwise get inferred return type from function body and report error only if it is not void / anytype + if (!hasExplicitReturn) { + return; + } + const inferredReturnType = getReturnTypeOfSignature(getSignatureFromDeclaration(func)); + if (isUnwrappedReturnTypeVoidOrAny(func, inferredReturnType)) { + return; + } } - const inferredReturnType = getReturnTypeOfSignature(getSignatureFromDeclaration(func)); - if (isUnwrappedReturnTypeVoidOrAny(func, inferredReturnType)) { - return; - } + error(errorNode, Diagnostics.Not_all_code_paths_return_a_value); } - error(errorNode, Diagnostics.Not_all_code_paths_return_a_value); } } @@ -32894,52 +32900,54 @@ namespace ts { return undefinedWideningType; } - function checkAwaitExpression(node: AwaitExpression): Type { + function checkAwaitExpressionGrammar(node: AwaitExpression): void { // Grammar checking - if (produceDiagnostics) { - const container = getContainingFunctionOrClassStaticBlock(node); - if (container && isClassStaticBlockDeclaration(container)) { - error(node, Diagnostics.Await_expression_cannot_be_used_inside_a_class_static_block); - } - else if (!(node.flags & NodeFlags.AwaitContext)) { - if (isInTopLevelContext(node)) { - const sourceFile = getSourceFileOfNode(node); - if (!hasParseDiagnostics(sourceFile)) { - let span: TextSpan | undefined; - if (!isEffectiveExternalModule(sourceFile, compilerOptions)) { - if (!span) span = getSpanOfTokenAtPosition(sourceFile, node.pos); - const diagnostic = createFileDiagnostic(sourceFile, span.start, span.length, - Diagnostics.await_expressions_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module); - diagnostics.add(diagnostic); - } - if ((moduleKind !== ModuleKind.ES2022 && moduleKind !== ModuleKind.ESNext && moduleKind !== ModuleKind.System && !(moduleKind === ModuleKind.NodeNext && getSourceFileOfNode(node).impliedNodeFormat === ModuleKind.ESNext)) || languageVersion < ScriptTarget.ES2017) { - span = getSpanOfTokenAtPosition(sourceFile, node.pos); - const diagnostic = createFileDiagnostic(sourceFile, span.start, span.length, - Diagnostics.Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_or_nodenext_and_the_target_option_is_set_to_es2017_or_higher); - diagnostics.add(diagnostic); - } + const container = getContainingFunctionOrClassStaticBlock(node); + if (container && isClassStaticBlockDeclaration(container)) { + error(node, Diagnostics.Await_expression_cannot_be_used_inside_a_class_static_block); + } + else if (!(node.flags & NodeFlags.AwaitContext)) { + if (isInTopLevelContext(node)) { + const sourceFile = getSourceFileOfNode(node); + if (!hasParseDiagnostics(sourceFile)) { + let span: TextSpan | undefined; + if (!isEffectiveExternalModule(sourceFile, compilerOptions)) { + if (!span) span = getSpanOfTokenAtPosition(sourceFile, node.pos); + const diagnostic = createFileDiagnostic(sourceFile, span.start, span.length, + Diagnostics.await_expressions_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module); + diagnostics.add(diagnostic); } - } - else { - // use of 'await' in non-async function - const sourceFile = getSourceFileOfNode(node); - if (!hasParseDiagnostics(sourceFile)) { - const span = getSpanOfTokenAtPosition(sourceFile, node.pos); - const diagnostic = createFileDiagnostic(sourceFile, span.start, span.length, Diagnostics.await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules); - if (container && container.kind !== SyntaxKind.Constructor && (getFunctionFlags(container) & FunctionFlags.Async) === 0) { - const relatedInfo = createDiagnosticForNode(container, Diagnostics.Did_you_mean_to_mark_this_function_as_async); - addRelatedInfo(diagnostic, relatedInfo); - } + if ((moduleKind !== ModuleKind.ES2022 && moduleKind !== ModuleKind.ESNext && moduleKind !== ModuleKind.System && !(moduleKind === ModuleKind.NodeNext && getSourceFileOfNode(node).impliedNodeFormat === ModuleKind.ESNext)) || languageVersion < ScriptTarget.ES2017) { + span = getSpanOfTokenAtPosition(sourceFile, node.pos); + const diagnostic = createFileDiagnostic(sourceFile, span.start, span.length, + Diagnostics.Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_or_nodenext_and_the_target_option_is_set_to_es2017_or_higher); diagnostics.add(diagnostic); } } } - - if (isInParameterInitializerBeforeContainingFunction(node)) { - error(node, Diagnostics.await_expressions_cannot_be_used_in_a_parameter_initializer); + else { + // use of 'await' in non-async function + const sourceFile = getSourceFileOfNode(node); + if (!hasParseDiagnostics(sourceFile)) { + const span = getSpanOfTokenAtPosition(sourceFile, node.pos); + const diagnostic = createFileDiagnostic(sourceFile, span.start, span.length, Diagnostics.await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules); + if (container && container.kind !== SyntaxKind.Constructor && (getFunctionFlags(container) & FunctionFlags.Async) === 0) { + const relatedInfo = createDiagnosticForNode(container, Diagnostics.Did_you_mean_to_mark_this_function_as_async); + addRelatedInfo(diagnostic, relatedInfo); + } + diagnostics.add(diagnostic); + } } } + if (isInParameterInitializerBeforeContainingFunction(node)) { + error(node, Diagnostics.await_expressions_cannot_be_used_in_a_parameter_initializer); + } + } + + function checkAwaitExpression(node: AwaitExpression): Type { + addLazyDiagnostic(() => checkAwaitExpressionGrammar(node)); + const operandType = checkExpression(node.expression); const awaitedType = checkAwaitedType(operandType, /*withAlias*/ true, node, Diagnostics.Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); if (awaitedType === operandType && !isErrorType(awaitedType) && !(operandType.flags & TypeFlags.AnyOrUnknown)) { @@ -33857,7 +33865,11 @@ namespace ts { } function checkAssignmentOperator(valueType: Type): void { - if (produceDiagnostics && isAssignmentOperator(operator)) { + if (isAssignmentOperator(operator)) { + addLazyDiagnostic(checkAssignmentOperatorWorker); + } + + function checkAssignmentOperatorWorker() { // TypeScript 1.0 spec (April 2014): 4.17 // An assignment of the form // VarExpr = ValueExpr @@ -33978,16 +33990,7 @@ namespace ts { } function checkYieldExpression(node: YieldExpression): Type { - // Grammar checking - if (produceDiagnostics) { - if (!(node.flags & NodeFlags.YieldContext)) { - grammarErrorOnFirstToken(node, Diagnostics.A_yield_expression_is_only_allowed_in_a_generator_body); - } - - if (isInParameterInitializerBeforeContainingFunction(node)) { - error(node, Diagnostics.yield_expressions_cannot_be_used_in_a_parameter_initializer); - } - } + addLazyDiagnostic(checkYieldExpressionGrammar); const func = getContainingFunction(node); if (!func) return anyType; @@ -34038,14 +34041,26 @@ namespace ts { let type = getContextualIterationType(IterationTypeKind.Next, func); if (!type) { type = anyType; - if (produceDiagnostics && noImplicitAny && !expressionResultIsUnused(node)) { - const contextualType = getContextualType(node); - if (!contextualType || isTypeAny(contextualType)) { - error(node, Diagnostics.yield_expression_implicitly_results_in_an_any_type_because_its_containing_generator_lacks_a_return_type_annotation); + addLazyDiagnostic(() => { + if (noImplicitAny && !expressionResultIsUnused(node)) { + const contextualType = getContextualType(node); + if (!contextualType || isTypeAny(contextualType)) { + error(node, Diagnostics.yield_expression_implicitly_results_in_an_any_type_because_its_containing_generator_lacks_a_return_type_annotation); + } } - } + }); } return type; + + function checkYieldExpressionGrammar() { + if (!(node.flags & NodeFlags.YieldContext)) { + grammarErrorOnFirstToken(node, Diagnostics.A_yield_expression_is_only_allowed_in_a_generator_body); + } + + if (isInParameterInitializerBeforeContainingFunction(node)) { + error(node, Diagnostics.yield_expressions_cannot_be_used_in_a_parameter_initializer); + } + } } function checkConditionalExpression(node: ConditionalExpression, checkMode?: CheckMode): Type { @@ -34653,6 +34668,7 @@ namespace ts { function checkTypeParameter(node: TypeParameterDeclaration) { // Grammar Checking + checkGrammarModifiers(node); if (node.expression) { grammarErrorOnFirstToken(node.expression, Diagnostics.Type_expected); } @@ -34670,9 +34686,19 @@ namespace ts { if (constraintType && defaultType) { checkTypeAssignableTo(defaultType, getTypeWithThisArgument(instantiateType(constraintType, makeUnaryTypeMapper(typeParameter, defaultType)), defaultType), node.default, Diagnostics.Type_0_does_not_satisfy_the_constraint_1); } - if (produceDiagnostics) { - checkTypeNameIsReserved(node.name, Diagnostics.Type_parameter_name_cannot_be_0); + if (node.parent.kind === SyntaxKind.InterfaceDeclaration || node.parent.kind === SyntaxKind.ClassDeclaration || node.parent.kind === SyntaxKind.TypeAliasDeclaration) { + const modifiers = getVarianceModifiers(typeParameter); + if (modifiers === ModifierFlags.In || modifiers === ModifierFlags.Out) { + const symbol = getSymbolOfNode(node.parent); + const source = createMarkerType(symbol, typeParameter, modifiers === ModifierFlags.Out ? markerSubType : markerSuperType); + const target = createMarkerType(symbol, typeParameter, modifiers === ModifierFlags.Out ? markerSuperType : markerSubType); + const saveVarianceTypeParameter = typeParameter; + varianceTypeParameter = typeParameter; + checkTypeAssignableTo(source, target, node, Diagnostics.Type_0_is_not_assignable_to_type_1_as_implied_by_variance_annotation); + varianceTypeParameter = saveVarianceTypeParameter; + } } + addLazyDiagnostic(() => checkTypeNameIsReserved(node.name, Diagnostics.Type_parameter_name_cannot_be_0)); } function checkParameter(node: ParameterDeclaration) { @@ -34853,7 +34879,9 @@ namespace ts { checkSourceElement(node.type); } - if (produceDiagnostics) { + addLazyDiagnostic(checkSignatureDeclarationDiagnostics); + + function checkSignatureDeclarationDiagnostics() { checkCollisionWithArgumentsInGeneratedCode(node); const returnTypeNode = getEffectiveReturnTypeNode(node); if (noImplicitAny && !returnTypeNode) { @@ -35163,9 +35191,9 @@ namespace ts { return; } - if (!produceDiagnostics) { - return; - } + addLazyDiagnostic(checkConstructorDeclarationDiagnostics); + + return; function isInstancePropertyWithInitializerOrPrivateIdentifierProperty(n: Node): boolean { if (isPrivateIdentifierClassElementDeclaration(n)) { @@ -35176,59 +35204,61 @@ namespace ts { !!(n as PropertyDeclaration).initializer; } - // TS 1.0 spec (April 2014): 8.3.2 - // Constructors of classes with no extends clause may not contain super calls, whereas - // constructors of derived classes must contain at least one super call somewhere in their function body. - const containingClassDecl = node.parent as ClassDeclaration; - if (getClassExtendsHeritageElement(containingClassDecl)) { - captureLexicalThis(node.parent, containingClassDecl); - const classExtendsNull = classDeclarationExtendsNull(containingClassDecl); - const superCall = findFirstSuperCall(node.body!); - if (superCall) { - if (classExtendsNull) { - error(superCall, Diagnostics.A_constructor_cannot_contain_a_super_call_when_its_class_extends_null); - } - - // A super call must be root-level in a constructor if both of the following are true: - // - The containing class is a derived class. - // - The constructor declares parameter properties - // or the containing class declares instance member variables with initializers. - - const superCallShouldBeRootLevel = - (getEmitScriptTarget(compilerOptions) !== ScriptTarget.ESNext || !useDefineForClassFields) && - (some((node.parent as ClassDeclaration).members, isInstancePropertyWithInitializerOrPrivateIdentifierProperty) || - some(node.parameters, p => hasSyntacticModifier(p, ModifierFlags.ParameterPropertyModifier))); - - if (superCallShouldBeRootLevel) { - // Until we have better flow analysis, it is an error to place the super call within any kind of block or conditional - // See GH #8277 - if (!superCallIsRootLevelInConstructor(superCall, node.body!)) { - error(superCall, Diagnostics.A_super_call_must_be_a_root_level_statement_within_a_constructor_of_a_derived_class_that_contains_initialized_properties_parameter_properties_or_private_identifiers); + function checkConstructorDeclarationDiagnostics() { + // TS 1.0 spec (April 2014): 8.3.2 + // Constructors of classes with no extends clause may not contain super calls, whereas + // constructors of derived classes must contain at least one super call somewhere in their function body. + const containingClassDecl = node.parent as ClassDeclaration; + if (getClassExtendsHeritageElement(containingClassDecl)) { + captureLexicalThis(node.parent, containingClassDecl); + const classExtendsNull = classDeclarationExtendsNull(containingClassDecl); + const superCall = findFirstSuperCall(node.body!); + if (superCall) { + if (classExtendsNull) { + error(superCall, Diagnostics.A_constructor_cannot_contain_a_super_call_when_its_class_extends_null); } - // Skip past any prologue directives to check statements for referring to 'super' or 'this' before a super call - else { - let superCallStatement: ExpressionStatement | undefined; - for (const statement of node.body!.statements) { - if (isExpressionStatement(statement) && isSuperCall(skipOuterExpressions(statement.expression))) { - superCallStatement = statement; - break; - } - if (!isPrologueDirective(statement) && nodeImmediatelyReferencesSuperOrThis(statement)) { - break; - } - } + // A super call must be root-level in a constructor if both of the following are true: + // - The containing class is a derived class. + // - The constructor declares parameter properties + // or the containing class declares instance member variables with initializers. + const superCallShouldBeRootLevel = + (getEmitScriptTarget(compilerOptions) !== ScriptTarget.ESNext || !useDefineForClassFields) && + (some((node.parent as ClassDeclaration).members, isInstancePropertyWithInitializerOrPrivateIdentifierProperty) || + some(node.parameters, p => hasSyntacticModifier(p, ModifierFlags.ParameterPropertyModifier))); + + if (superCallShouldBeRootLevel) { // Until we have better flow analysis, it is an error to place the super call within any kind of block or conditional // See GH #8277 - if (superCallStatement === undefined) { - error(node, Diagnostics.A_super_call_must_be_the_first_statement_in_the_constructor_to_refer_to_super_or_this_when_a_derived_class_contains_initialized_properties_parameter_properties_or_private_identifiers); + if (!superCallIsRootLevelInConstructor(superCall, node.body!)) { + error(superCall, Diagnostics.A_super_call_must_be_a_root_level_statement_within_a_constructor_of_a_derived_class_that_contains_initialized_properties_parameter_properties_or_private_identifiers); + } + // Skip past any prologue directives to check statements for referring to 'super' or 'this' before a super call + else { + let superCallStatement: ExpressionStatement | undefined; + + for (const statement of node.body!.statements) { + if (isExpressionStatement(statement) && isSuperCall(skipOuterExpressions(statement.expression))) { + superCallStatement = statement; + break; + } + if (!isPrologueDirective(statement) && nodeImmediatelyReferencesSuperOrThis(statement)) { + break; + } + } + + // Until we have better flow analysis, it is an error to place the super call within any kind of block or conditional + // See GH #8277 + if (superCallStatement === undefined) { + error(node, Diagnostics.A_super_call_must_be_the_first_statement_in_the_constructor_to_refer_to_super_or_this_when_a_derived_class_contains_initialized_properties_parameter_properties_or_private_identifiers); + } } } } - } - else if (!classExtendsNull) { - error(node, Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call); + else if (!classExtendsNull) { + error(node, Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call); + } } } } @@ -35251,7 +35281,11 @@ namespace ts { } function checkAccessorDeclaration(node: AccessorDeclaration) { - if (produceDiagnostics) { + addLazyDiagnostic(checkAccessorDeclarationDiagnostics); + checkSourceElement(node.body); + setNodeLinksForPrivateIdentifierScope(node); + + function checkAccessorDeclarationDiagnostics() { // Grammar checking accessors if (!checkGrammarFunctionLikeDeclaration(node) && !checkGrammarAccessor(node)) checkGrammarComputedPropertyName(node.name); @@ -35303,8 +35337,6 @@ namespace ts { checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType); } } - checkSourceElement(node.body); - setNodeLinksForPrivateIdentifierScope(node); } function checkMissingDeclaration(node: Node) { @@ -35357,11 +35389,13 @@ namespace ts { forEach(node.typeArguments, checkSourceElement); const type = getTypeFromTypeReference(node); if (!isErrorType(type)) { - if (node.typeArguments && produceDiagnostics) { - const typeParameters = getTypeParametersForTypeReference(node); - if (typeParameters) { - checkTypeArgumentConstraints(node, typeParameters); - } + if (node.typeArguments) { + addLazyDiagnostic(() => { + const typeParameters = getTypeParametersForTypeReference(node); + if (typeParameters) { + checkTypeArgumentConstraints(node, typeParameters); + } + }); } const symbol = getNodeLinks(node).resolvedSymbol; if (symbol) { @@ -35394,7 +35428,9 @@ namespace ts { function checkTypeLiteral(node: TypeLiteralNode) { forEach(node.members, checkSourceElement); - if (produceDiagnostics) { + addLazyDiagnostic(checkTypeLiteralDiagnostics); + + function checkTypeLiteralDiagnostics() { const type = getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); checkIndexConstraints(type, type.symbol); checkTypeForDuplicateIndexSignatures(node); @@ -35605,10 +35641,10 @@ namespace ts { } function checkFunctionOrConstructorSymbol(symbol: Symbol): void { - if (!produceDiagnostics) { - return; - } + addLazyDiagnostic(() => checkFunctionOrConstructorSymbolWorker(symbol)); + } + function checkFunctionOrConstructorSymbolWorker(symbol: Symbol): void { function getCanonicalOverload(overloads: Declaration[], implementation: FunctionLikeDeclaration | undefined): Declaration { // Consider the canonical set of flags to be the flags of the bodyDeclaration or the first declaration // Error on all deviations from this canonical set of flags @@ -35856,10 +35892,10 @@ namespace ts { } function checkExportsOnMergedDeclarations(node: Declaration): void { - if (!produceDiagnostics) { - return; - } + addLazyDiagnostic(() => checkExportsOnMergedDeclarationsWorker(node)); + } + function checkExportsOnMergedDeclarationsWorker(node: Declaration): void { // if localSymbol is defined on node then node itself is exported - check is required let symbol = node.localSymbol; if (!symbol) { @@ -36413,21 +36449,32 @@ namespace ts { * marked as referenced to prevent import elision. */ function markTypeNodeAsReferenced(node: TypeNode) { - markEntityNameOrEntityExpressionAsReference(node && getEntityNameFromTypeNode(node)); + markEntityNameOrEntityExpressionAsReference(node && getEntityNameFromTypeNode(node), /*forDecoratorMetadata*/ false); } - function markEntityNameOrEntityExpressionAsReference(typeName: EntityNameOrEntityNameExpression | undefined) { + function markEntityNameOrEntityExpressionAsReference(typeName: EntityNameOrEntityNameExpression | undefined, forDecoratorMetadata: boolean) { if (!typeName) return; const rootName = getFirstIdentifier(typeName); const meaning = (typeName.kind === SyntaxKind.Identifier ? SymbolFlags.Type : SymbolFlags.Namespace) | SymbolFlags.Alias; const rootSymbol = resolveName(rootName, rootName.escapedText, meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isReference*/ true); - if (rootSymbol - && rootSymbol.flags & SymbolFlags.Alias - && symbolIsValue(rootSymbol) - && !isConstEnumOrConstEnumOnlyModule(resolveAlias(rootSymbol)) - && !getTypeOnlyAliasDeclaration(rootSymbol)) { - markAliasSymbolAsReferenced(rootSymbol); + if (rootSymbol && rootSymbol.flags & SymbolFlags.Alias) { + if (symbolIsValue(rootSymbol) + && !isConstEnumOrConstEnumOnlyModule(resolveAlias(rootSymbol)) + && !getTypeOnlyAliasDeclaration(rootSymbol)) { + markAliasSymbolAsReferenced(rootSymbol); + } + else if (forDecoratorMetadata + && compilerOptions.isolatedModules + && getEmitModuleKind(compilerOptions) >= ModuleKind.ES2015 + && !symbolIsValue(rootSymbol) + && !some(rootSymbol.declarations, isTypeOnlyImportOrExportDeclaration)) { + const diag = error(typeName, Diagnostics.A_type_referenced_in_a_decorated_signature_must_be_imported_with_import_type_or_a_namespace_import_when_isolatedModules_and_emitDecoratorMetadata_are_enabled); + const aliasDeclaration = find(rootSymbol.declarations || emptyArray, isAliasSymbolDeclaration); + if (aliasDeclaration) { + addRelatedInfo(diag, createDiagnosticForNode(aliasDeclaration, Diagnostics._0_was_imported_here, idText(rootName))); + } + } } } @@ -36441,7 +36488,7 @@ namespace ts { function markDecoratorMedataDataTypeNodeAsReferenced(node: TypeNode | undefined): void { const entityName = getEntityNameForDecoratorMetadata(node); if (entityName && isEntityName(entityName)) { - markEntityNameOrEntityExpressionAsReference(entityName); + markEntityNameOrEntityExpressionAsReference(entityName, /*forDecoratorMetadata*/ true); } } @@ -36576,7 +36623,9 @@ namespace ts { } function checkFunctionDeclaration(node: FunctionDeclaration): void { - if (produceDiagnostics) { + addLazyDiagnostic(checkFunctionDeclarationDiagnostics); + + function checkFunctionDeclarationDiagnostics() { checkFunctionOrMethodDeclaration(node); checkGrammarForGenerator(node); checkCollisionsForDeclarationName(node, node.name); @@ -36615,10 +36664,14 @@ namespace ts { } function checkJSDocFunctionType(node: JSDocFunctionType): void { - if (produceDiagnostics && !node.type && !isJSDocConstructSignature(node)) { - reportImplicitAny(node, anyType); - } + addLazyDiagnostic(checkJSDocFunctionTypeImplicitAny); checkSignatureDeclaration(node); + + function checkJSDocFunctionTypeImplicitAny() { + if (!node.type && !isJSDocConstructSignature(node)) { + reportImplicitAny(node, anyType); + } + } } function checkJSDocImplementsTag(node: JSDocImplementsTag): void { @@ -36714,20 +36767,7 @@ namespace ts { checkSourceElement(body); checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, getReturnTypeFromAnnotation(node)); - if (produceDiagnostics && !getEffectiveReturnTypeNode(node)) { - // Report an implicit any error if there is no body, no explicit return type, and node is not a private method - // in an ambient context - if (nodeIsMissing(body) && !isPrivateWithinAmbient(node)) { - reportImplicitAny(node, anyType); - } - - if (functionFlags & FunctionFlags.Generator && nodeIsPresent(body)) { - // A generator with a body and no type annotation can still cause errors. It can error if the - // yielded values have no common supertype, or it can give an implicit any error if it has no - // yielded values. The only way to trigger these errors is to try checking its return type. - getReturnTypeOfSignature(getSignatureFromDeclaration(node)); - } - } + addLazyDiagnostic(checkFunctionOrMethodDeclarationDiagnostics); // A js function declaration can have a @type tag instead of a return type node, but that type must have a call signature if (isInJSFile(node)) { @@ -36736,11 +36776,30 @@ namespace ts { error(typeTag.typeExpression.type, Diagnostics.The_type_of_a_function_declaration_must_match_the_function_s_signature); } } + + function checkFunctionOrMethodDeclarationDiagnostics() { + if (!getEffectiveReturnTypeNode(node)) { + // Report an implicit any error if there is no body, no explicit return type, and node is not a private method + // in an ambient context + if (nodeIsMissing(body) && !isPrivateWithinAmbient(node)) { + reportImplicitAny(node, anyType); + } + + if (functionFlags & FunctionFlags.Generator && nodeIsPresent(body)) { + // A generator with a body and no type annotation can still cause errors. It can error if the + // yielded values have no common supertype, or it can give an implicit any error if it has no + // yielded values. The only way to trigger these errors is to try checking its return type. + getReturnTypeOfSignature(getSignatureFromDeclaration(node)); + } + } + } } function registerForUnusedIdentifiersCheck(node: PotentiallyUnusedIdentifier): void { - // May be in a call such as getTypeOfNode that happened to call this. But potentiallyUnusedIdentifiers is only defined in the scope of `checkSourceFile`. - if (produceDiagnostics) { + addLazyDiagnostic(registerForUnusedIdentifiersCheckDiagnostics); + + function registerForUnusedIdentifiersCheckDiagnostics() { + // May be in a call such as getTypeOfNode that happened to call this. But potentiallyUnusedIdentifiers is only defined in the scope of `checkSourceFile`. const sourceFile = getSourceFileOfNode(node); let potentiallyUnusedIdentifiers = allPotentiallyUnusedIdentifiers.get(sourceFile.path); if (!potentiallyUnusedIdentifiers) { @@ -37582,6 +37641,7 @@ namespace ts { (condExpr.operatorToken.kind === SyntaxKind.BarBarToken || condExpr.operatorToken.kind === SyntaxKind.AmpersandAmpersandToken) ? condExpr.right : condExpr; + if (isModuleExportsAccessExpression(location)) return; const type = checkTruthinessExpression(location); const isPropertyExpressionCast = isPropertyAccessExpression(location) && isTypeAssertion(location.expression); if (getFalsyFlags(type) || isPropertyExpressionCast) return; @@ -38715,26 +38775,32 @@ namespace ts { } } - if (produceDiagnostics && clause.kind === SyntaxKind.CaseClause) { - // TypeScript 1.0 spec (April 2014): 5.9 - // In a 'switch' statement, each 'case' expression must be of a type that is comparable - // to or from the type of the 'switch' expression. - let caseType = checkExpression(clause.expression); - const caseIsLiteral = isLiteralType(caseType); - let comparedExpressionType = expressionType; - if (!caseIsLiteral || !expressionIsLiteral) { - caseType = caseIsLiteral ? getBaseTypeOfLiteralType(caseType) : caseType; - comparedExpressionType = getBaseTypeOfLiteralType(expressionType); - } - if (!isTypeEqualityComparableTo(comparedExpressionType, caseType)) { - // expressionType is not comparable to caseType, try the reversed check and report errors if it fails - checkTypeComparableTo(caseType, comparedExpressionType, clause.expression, /*headMessage*/ undefined); - } + if (clause.kind === SyntaxKind.CaseClause) { + addLazyDiagnostic(createLazyCaseClauseDiagnostics(clause)); } forEach(clause.statements, checkSourceElement); if (compilerOptions.noFallthroughCasesInSwitch && clause.fallthroughFlowNode && isReachableFlowNode(clause.fallthroughFlowNode)) { error(clause, Diagnostics.Fallthrough_case_in_switch); } + + function createLazyCaseClauseDiagnostics(clause: CaseClause) { + return () => { + // TypeScript 1.0 spec (April 2014): 5.9 + // In a 'switch' statement, each 'case' expression must be of a type that is comparable + // to or from the type of the 'switch' expression. + let caseType = checkExpression(clause.expression); + const caseIsLiteral = isLiteralType(caseType); + let comparedExpressionType = expressionType; + if (!caseIsLiteral || !expressionIsLiteral) { + caseType = caseIsLiteral ? getBaseTypeOfLiteralType(caseType) : caseType; + comparedExpressionType = getBaseTypeOfLiteralType(expressionType); + } + if (!isTypeEqualityComparableTo(comparedExpressionType, caseType)) { + // expressionType is not comparable to caseType, try the reversed check and report errors if it fails + checkTypeComparableTo(caseType, comparedExpressionType, clause.expression, /*headMessage*/ undefined); + } + }; + } }); if (node.caseBlock.locals) { registerForUnusedIdentifiersCheck(node.caseBlock); @@ -38959,27 +39025,31 @@ namespace ts { * Check each type parameter and check that type parameters have no duplicate type parameter declarations */ function checkTypeParameters(typeParameterDeclarations: readonly TypeParameterDeclaration[] | undefined) { + let seenDefault = false; if (typeParameterDeclarations) { - let seenDefault = false; for (let i = 0; i < typeParameterDeclarations.length; i++) { const node = typeParameterDeclarations[i]; checkTypeParameter(node); - if (produceDiagnostics) { - if (node.default) { - seenDefault = true; - checkTypeParametersNotReferenced(node.default, typeParameterDeclarations, i); - } - else if (seenDefault) { - error(node, Diagnostics.Required_type_parameters_may_not_follow_optional_type_parameters); - } - for (let j = 0; j < i; j++) { - if (typeParameterDeclarations[j].symbol === node.symbol) { - error(node.name, Diagnostics.Duplicate_identifier_0, declarationNameToString(node.name)); - } + addLazyDiagnostic(createCheckTypeParameterDiagnostic(node, i)); + } + } + + function createCheckTypeParameterDiagnostic(node: TypeParameterDeclaration, i: number) { + return () => { + if (node.default) { + seenDefault = true; + checkTypeParametersNotReferenced(node.default, typeParameterDeclarations!, i); + } + else if (seenDefault) { + error(node, Diagnostics.Required_type_parameters_may_not_follow_optional_type_parameters); + } + for (let j = 0; j < i; j++) { + if (typeParameterDeclarations![j].symbol === node.symbol) { + error(node.name, Diagnostics.Duplicate_identifier_0, declarationNameToString(node.name)); } } - } + }; } } @@ -39129,50 +39199,52 @@ namespace ts { } const baseTypes = getBaseTypes(type); - if (baseTypes.length && produceDiagnostics) { - const baseType = baseTypes[0]; - const baseConstructorType = getBaseConstructorTypeOfClass(type); - const staticBaseType = getApparentType(baseConstructorType); - checkBaseTypeAccessibility(staticBaseType, baseTypeNode); - checkSourceElement(baseTypeNode.expression); - if (some(baseTypeNode.typeArguments)) { - forEach(baseTypeNode.typeArguments, checkSourceElement); - for (const constructor of getConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode)) { - if (!checkTypeArgumentConstraints(baseTypeNode, constructor.typeParameters!)) { - break; + if (baseTypes.length) { + addLazyDiagnostic(() => { + const baseType = baseTypes[0]; + const baseConstructorType = getBaseConstructorTypeOfClass(type); + const staticBaseType = getApparentType(baseConstructorType); + checkBaseTypeAccessibility(staticBaseType, baseTypeNode); + checkSourceElement(baseTypeNode.expression); + if (some(baseTypeNode.typeArguments)) { + forEach(baseTypeNode.typeArguments, checkSourceElement); + for (const constructor of getConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode)) { + if (!checkTypeArgumentConstraints(baseTypeNode, constructor.typeParameters!)) { + break; + } } } - } - const baseWithThis = getTypeWithThisArgument(baseType, type.thisType); - if (!checkTypeAssignableTo(typeWithThis, baseWithThis, /*errorNode*/ undefined)) { - issueMemberSpecificError(node, typeWithThis, baseWithThis, Diagnostics.Class_0_incorrectly_extends_base_class_1); - } - else { - // Report static side error only when instance type is assignable - checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, - Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); - } - if (baseConstructorType.flags & TypeFlags.TypeVariable) { - if (!isMixinConstructorType(staticType)) { - error(node.name || node, Diagnostics.A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any); + const baseWithThis = getTypeWithThisArgument(baseType, type.thisType); + if (!checkTypeAssignableTo(typeWithThis, baseWithThis, /*errorNode*/ undefined)) { + issueMemberSpecificError(node, typeWithThis, baseWithThis, Diagnostics.Class_0_incorrectly_extends_base_class_1); } else { - const constructSignatures = getSignaturesOfType(baseConstructorType, SignatureKind.Construct); - if (constructSignatures.some(signature => signature.flags & SignatureFlags.Abstract) && !hasSyntacticModifier(node, ModifierFlags.Abstract)) { - error(node.name || node, Diagnostics.A_mixin_class_that_extends_from_a_type_variable_containing_an_abstract_construct_signature_must_also_be_declared_abstract); + // Report static side error only when instance type is assignable + checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, + Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); + } + if (baseConstructorType.flags & TypeFlags.TypeVariable) { + if (!isMixinConstructorType(staticType)) { + error(node.name || node, Diagnostics.A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any); + } + else { + const constructSignatures = getSignaturesOfType(baseConstructorType, SignatureKind.Construct); + if (constructSignatures.some(signature => signature.flags & SignatureFlags.Abstract) && !hasSyntacticModifier(node, ModifierFlags.Abstract)) { + error(node.name || node, Diagnostics.A_mixin_class_that_extends_from_a_type_variable_containing_an_abstract_construct_signature_must_also_be_declared_abstract); + } } } - } - if (!(staticBaseType.symbol && staticBaseType.symbol.flags & SymbolFlags.Class) && !(baseConstructorType.flags & TypeFlags.TypeVariable)) { - // When the static base type is a "class-like" constructor function (but not actually a class), we verify - // that all instantiated base constructor signatures return the same type. - const constructors = getInstantiatedConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); - if (forEach(constructors, sig => !isJSConstructor(sig.declaration) && !isTypeIdenticalTo(getReturnTypeOfSignature(sig), baseType))) { - error(baseTypeNode.expression, Diagnostics.Base_constructors_must_all_have_the_same_return_type); + if (!(staticBaseType.symbol && staticBaseType.symbol.flags & SymbolFlags.Class) && !(baseConstructorType.flags & TypeFlags.TypeVariable)) { + // When the static base type is a "class-like" constructor function (but not actually a class), we verify + // that all instantiated base constructor signatures return the same type. + const constructors = getInstantiatedConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); + if (forEach(constructors, sig => !isJSConstructor(sig.declaration) && !isTypeIdenticalTo(getReturnTypeOfSignature(sig), baseType))) { + error(baseTypeNode.expression, Diagnostics.Base_constructors_must_all_have_the_same_return_type); + } } - } - checkKindsOfPropertyMemberOverrides(type, baseType); + checkKindsOfPropertyMemberOverrides(type, baseType); + }); } } @@ -39185,31 +39257,35 @@ namespace ts { error(typeRefNode.expression, Diagnostics.A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments); } checkTypeReferenceNode(typeRefNode); - if (produceDiagnostics) { - const t = getReducedType(getTypeFromTypeNode(typeRefNode)); - if (!isErrorType(t)) { - if (isValidBaseType(t)) { - const genericDiag = t.symbol && t.symbol.flags & SymbolFlags.Class ? - Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass : - Diagnostics.Class_0_incorrectly_implements_interface_1; - const baseWithThis = getTypeWithThisArgument(t, type.thisType); - if (!checkTypeAssignableTo(typeWithThis, baseWithThis, /*errorNode*/ undefined)) { - issueMemberSpecificError(node, typeWithThis, baseWithThis, genericDiag); - } - } - else { - error(typeRefNode, Diagnostics.A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_members); - } - } - } + addLazyDiagnostic(createImplementsDiagnostics(typeRefNode)); } } - if (produceDiagnostics) { + addLazyDiagnostic(() => { checkIndexConstraints(type, symbol); checkIndexConstraints(staticType, symbol, /*isStaticIndex*/ true); checkTypeForDuplicateIndexSignatures(node); checkPropertyInitialization(node); + }); + + function createImplementsDiagnostics(typeRefNode: ExpressionWithTypeArguments) { + return () => { + const t = getReducedType(getTypeFromTypeNode(typeRefNode)); + if (!isErrorType(t)) { + if (isValidBaseType(t)) { + const genericDiag = t.symbol && t.symbol.flags & SymbolFlags.Class ? + Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass : + Diagnostics.Class_0_incorrectly_implements_interface_1; + const baseWithThis = getTypeWithThisArgument(t, type.thisType); + if (!checkTypeAssignableTo(typeWithThis, baseWithThis, /*errorNode*/ undefined)) { + issueMemberSpecificError(node, typeWithThis, baseWithThis, genericDiag); + } + } + else { + error(typeRefNode, Diagnostics.A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_members); + } + } + }; } } @@ -39741,12 +39817,13 @@ namespace ts { return !(getFalsyFlags(flowType) & TypeFlags.Undefined); } + function checkInterfaceDeclaration(node: InterfaceDeclaration) { // Grammar checking if (!checkGrammarDecoratorsAndModifiers(node)) checkGrammarInterfaceDeclaration(node); checkTypeParameters(node.typeParameters); - if (produceDiagnostics) { + addLazyDiagnostic(() => { checkTypeNameIsReserved(node.name, Diagnostics.Interface_name_cannot_be_0); checkExportsOnMergedDeclarations(node); @@ -39767,7 +39844,7 @@ namespace ts { } } checkObjectTypeForDuplicateDeclarations(node); - } + }); forEach(getInterfaceBaseTypeNodes(node), heritageElement => { if (!isEntityNameExpression(heritageElement.expression) || isOptionalChain(heritageElement.expression)) { error(heritageElement.expression, Diagnostics.An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments); @@ -39777,10 +39854,10 @@ namespace ts { forEach(node.members, checkSourceElement); - if (produceDiagnostics) { + addLazyDiagnostic(() => { checkTypeForDuplicateIndexSignatures(node); registerForUnusedIdentifiersCheck(node); - } + }); } function checkTypeAliasDeclaration(node: TypeAliasDeclaration) { @@ -39977,10 +40054,10 @@ namespace ts { } function checkEnumDeclaration(node: EnumDeclaration) { - if (!produceDiagnostics) { - return; - } + addLazyDiagnostic(() => checkEnumDeclarationWorker(node)); + } + function checkEnumDeclarationWorker(node: EnumDeclaration) { // Grammar checking checkGrammarDecoratorsAndModifiers(node); @@ -40069,7 +40146,16 @@ namespace ts { } function checkModuleDeclaration(node: ModuleDeclaration) { - if (produceDiagnostics) { + if (node.body) { + checkSourceElement(node.body); + if (!isGlobalScopeAugmentation(node)) { + registerForUnusedIdentifiersCheck(node); + } + } + + addLazyDiagnostic(checkModuleDeclarationDiagnostics); + + function checkModuleDeclarationDiagnostics() { // Grammar checking const isGlobalAugmentation = isGlobalScopeAugmentation(node); const inAmbientContext = node.flags & NodeFlags.Ambient; @@ -40158,13 +40244,6 @@ namespace ts { } } } - - if (node.body) { - checkSourceElement(node.body); - if (!isGlobalScopeAugmentation(node)) { - registerForUnusedIdentifiersCheck(node); - } - } } function checkModuleAugmentationElement(node: Node, isGlobalAugmentation: boolean): void { @@ -40512,7 +40591,7 @@ namespace ts { return; } - if (!checkGrammarDecoratorsAndModifiers(node) && hasEffectiveModifiers(node)) { + if (!checkGrammarDecoratorsAndModifiers(node) && hasSyntacticModifiers(node)) { grammarErrorOnFirstToken(node, Diagnostics.An_export_declaration_cannot_have_modifiers); } @@ -41165,13 +41244,16 @@ namespace ts { registerForUnusedIdentifiersCheck(node); } - if (!node.isDeclarationFile && (compilerOptions.noUnusedLocals || compilerOptions.noUnusedParameters)) { - checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(node), (containingNode, kind, diag) => { - if (!containsParseError(containingNode) && unusedIsError(kind, !!(containingNode.flags & NodeFlags.Ambient))) { - diagnostics.add(diag); - } - }); - } + addLazyDiagnostic(() => { + // This relies on the results of other lazy diagnostics, so must be computed after them + if (!node.isDeclarationFile && (compilerOptions.noUnusedLocals || compilerOptions.noUnusedParameters)) { + checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(node), (containingNode, kind, diag) => { + if (!containsParseError(containingNode) && unusedIsError(kind, !!(containingNode.flags & NodeFlags.Ambient))) { + diagnostics.add(diag); + } + }); + } + }); if (compilerOptions.importsNotUsedAsValues === ImportsNotUsedAsValues.Error && !node.isDeclarationFile && @@ -41221,16 +41303,37 @@ namespace ts { } } + function ensurePendingDiagnosticWorkComplete() { + // Invoke any existing lazy diagnostics to add them, clear the backlog of diagnostics + for (const cb of deferredDiagnosticsCallbacks) { + cb(); + } + deferredDiagnosticsCallbacks = []; + } + + function checkSourceFileWithEagerDiagnostics(sourceFile: SourceFile) { + ensurePendingDiagnosticWorkComplete(); + // then setup diagnostics for immediate invocation (as we are about to collect them, and + // this avoids the overhead of longer-lived callbacks we don't need to allocate) + // This also serves to make the shift to possibly lazy diagnostics transparent to serial command-line scenarios + // (as in those cases, all the diagnostics will still be computed as the appropriate place in the tree, + // thus much more likely retaining the same union ordering as before we had lazy diagnostics) + const oldAddLazyDiagnostics = addLazyDiagnostic; + addLazyDiagnostic = cb => cb(); + checkSourceFile(sourceFile); + addLazyDiagnostic = oldAddLazyDiagnostics; + } + function getDiagnosticsWorker(sourceFile: SourceFile): Diagnostic[] { - throwIfNonDiagnosticsProducing(); if (sourceFile) { + ensurePendingDiagnosticWorkComplete(); // Some global diagnostics are deferred until they are needed and // may not be reported in the first call to getGlobalDiagnostics. // We should catch these changes and report them. const previousGlobalDiagnostics = diagnostics.getGlobalDiagnostics(); const previousGlobalDiagnosticsSize = previousGlobalDiagnostics.length; - checkSourceFile(sourceFile); + checkSourceFileWithEagerDiagnostics(sourceFile); const semanticDiagnostics = diagnostics.getDiagnostics(sourceFile.fileName); const currentGlobalDiagnostics = diagnostics.getGlobalDiagnostics(); @@ -41251,21 +41354,15 @@ namespace ts { // Global diagnostics are always added when a file is not provided to // getDiagnostics - forEach(host.getSourceFiles(), checkSourceFile); + forEach(host.getSourceFiles(), checkSourceFileWithEagerDiagnostics); return diagnostics.getDiagnostics(); } function getGlobalDiagnostics(): Diagnostic[] { - throwIfNonDiagnosticsProducing(); + ensurePendingDiagnosticWorkComplete(); return diagnostics.getGlobalDiagnostics(); } - function throwIfNonDiagnosticsProducing() { - if (!produceDiagnostics) { - throw new Error("Trying to get diagnostics from a type checker that does not produce them."); - } - } - // Language service support function getSymbolsInScope(location: Node, meaning: SymbolFlags): Symbol[] { @@ -43070,6 +43167,11 @@ namespace ts { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_an_index_signature, tokenToString(modifier.kind)); } } + if (modifier.kind !== SyntaxKind.InKeyword && modifier.kind !== SyntaxKind.OutKeyword) { + if (node.kind === SyntaxKind.TypeParameter) { + return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_type_parameter, tokenToString(modifier.kind)); + } + } switch (modifier.kind) { case SyntaxKind.ConstKeyword: if (node.kind !== SyntaxKind.EnumDeclaration) { @@ -43277,6 +43379,23 @@ namespace ts { flags |= ModifierFlags.Async; lastAsync = modifier; break; + + case SyntaxKind.InKeyword: + case SyntaxKind.OutKeyword: + const inOutFlag = modifier.kind === SyntaxKind.InKeyword ? ModifierFlags.In : ModifierFlags.Out; + const inOutText = modifier.kind === SyntaxKind.InKeyword ? "in" : "out"; + if (node.kind !== SyntaxKind.TypeParameter || (node.parent.kind !== SyntaxKind.InterfaceDeclaration && + node.parent.kind !== SyntaxKind.ClassDeclaration && node.parent.kind !== SyntaxKind.TypeAliasDeclaration)) { + return grammarErrorOnNode(modifier, Diagnostics._0_modifier_can_only_appear_on_a_type_parameter_of_a_class_interface_or_type_alias, inOutText); + } + if (flags & inOutFlag) { + return grammarErrorOnNode(modifier, Diagnostics._0_modifier_already_seen, inOutText); + } + if (inOutFlag & ModifierFlags.In && flags & ModifierFlags.Out) { + return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "in", "out"); + } + flags |= inOutFlag; + break; } } @@ -43336,6 +43455,7 @@ namespace ts { case SyntaxKind.FunctionExpression: case SyntaxKind.ArrowFunction: case SyntaxKind.Parameter: + case SyntaxKind.TypeParameter: return false; default: if (node.parent.kind === SyntaxKind.ModuleBlock || node.parent.kind === SyntaxKind.SourceFile) { @@ -43975,13 +44095,11 @@ namespace ts { if (node.type.kind !== SyntaxKind.SymbolKeyword) { return grammarErrorOnNode(node.type, Diagnostics._0_expected, tokenToString(SyntaxKind.SymbolKeyword)); } - let parent = walkUpParenthesizedTypes(node.parent); if (isInJSFile(parent) && isJSDocTypeExpression(parent)) { - parent = parent.parent; - if (isJSDocTypeTag(parent)) { - // walk up past JSDoc comment node - parent = parent.parent.parent; + const host = getJSDocHost(parent); + if (host) { + parent = getSingleVariableOfVariableStatement(host) || host; } } switch (parent.kind) { diff --git a/src/compiler/commandLineParser.ts b/src/compiler/commandLineParser.ts index 757ae3bba25..88d0f2d857f 100644 --- a/src/compiler/commandLineParser.ts +++ b/src/compiler/commandLineParser.ts @@ -568,7 +568,7 @@ namespace ts { category: Diagnostics.Projects, transpileOptionValue: undefined, defaultValueDescription: ".tsbuildinfo", - description: Diagnostics.Specify_the_folder_for_tsbuildinfo_incremental_compilation_files, + description: Diagnostics.Specify_the_path_to_tsbuildinfo_incremental_compilation_file, }, { name: "removeComments", @@ -2591,7 +2591,10 @@ namespace ts { * file to. e.g. outDir */ export function parseJsonSourceFileConfigFileContent(sourceFile: TsConfigSourceFile, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: readonly FileExtensionInfo[], extendedConfigCache?: Map, existingWatchOptions?: WatchOptions): ParsedCommandLine { - return parseJsonConfigFileContentWorker(/*json*/ undefined, sourceFile, host, basePath, existingOptions, existingWatchOptions, configFileName, resolutionStack, extraFileExtensions, extendedConfigCache); + tracing?.push(tracing.Phase.Parse, "parseJsonSourceFileConfigFileContent", { path: sourceFile.fileName }); + const result = parseJsonConfigFileContentWorker(/*json*/ undefined, sourceFile, host, basePath, existingOptions, existingWatchOptions, configFileName, resolutionStack, extraFileExtensions, extendedConfigCache); + tracing?.pop(); + return result; } /*@internal*/ @@ -3632,7 +3635,8 @@ namespace ts { case "boolean": return true; case "string": - return option.isFilePath ? "./" : ""; + const defaultValue = option.defaultValueDescription; + return option.isFilePath ? `./${defaultValue && typeof defaultValue === "string" ? defaultValue : ""}` : ""; case "list": return []; case "object": diff --git a/src/compiler/core.ts b/src/compiler/core.ts index d30eb0569a6..a3be6f976cd 100644 --- a/src/compiler/core.ts +++ b/src/compiler/core.ts @@ -301,7 +301,7 @@ namespace ts { array.length = outIndex; } - export function clear(array: {}[]): void { + export function clear(array: unknown[]): void { array.length = 0; } @@ -1644,7 +1644,7 @@ namespace ts { /** * Tests whether a value is an array. */ - export function isArray(value: any): value is readonly {}[] { + export function isArray(value: any): value is readonly unknown[] { return Array.isArray ? Array.isArray(value) : value instanceof Array; } @@ -1677,7 +1677,7 @@ namespace ts { } /** Does nothing. */ - export function noop(_?: {} | null | undefined): void { } + export function noop(_?: unknown): void { } /** Do nothing and return false */ export function returnFalse(): false { diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json index cf86150ee3b..c07ee5e190f 100644 --- a/src/compiler/diagnosticMessages.json +++ b/src/compiler/diagnosticMessages.json @@ -879,6 +879,18 @@ "category": "Error", "code": 1271 }, + "A type referenced in a decorated signature must be imported with 'import type' or a namespace import when 'isolatedModules' and 'emitDecoratorMetadata' are enabled.": { + "category": "Error", + "code": 1272 + }, + "'{0}' modifier cannot appear on a type parameter": { + "category": "Error", + "code": 1273 + }, + "'{0}' modifier can only appear on a type parameter of a class, interface or type alias": { + "category": "Error", + "code": 1274 + }, "'with' statements are not allowed in an async function block.": { "category": "Error", @@ -1494,6 +1506,10 @@ "category": "Error", "code": 2207 }, + "This type parameter probably needs an `extends object` constraint.": { + "category": "Error", + "code": 2208 + }, "Duplicate identifier '{0}'.": { "category": "Error", @@ -2723,6 +2739,10 @@ "category": "Error", "code": 2635 }, + "Type '{0}' is not assignable to type '{1}' as implied by variance annotation.": { + "category": "Error", + "code": 2636 + }, "Cannot augment module '{0}' with value exports because it resolves to a non-module entity.": { "category": "Error", @@ -5689,7 +5709,7 @@ "category": "Message", "code": 6706 }, - "Specify the folder for .tsbuildinfo incremental compilation files.": { + "Specify the path to .tsbuildinfo incremental compilation file.": { "category": "Message", "code": 6707 }, @@ -7174,6 +7194,7 @@ "code": 95173 }, + "No value exists in scope for the shorthand property '{0}'. Either declare one or provide an initializer.": { "category": "Error", "code": 18004 diff --git a/src/compiler/emitter.ts b/src/compiler/emitter.ts index 512ebab209f..62d3aaf19c6 100644 --- a/src/compiler/emitter.ts +++ b/src/compiler/emitter.ts @@ -2009,6 +2009,7 @@ namespace ts { // function emitTypeParameter(node: TypeParameterDeclaration) { + emitModifiers(node, node.modifiers); emit(node.name); if (node.constraint) { writeSpace(); diff --git a/src/compiler/factory/nodeFactory.ts b/src/compiler/factory/nodeFactory.ts index 633b4c2c5cd..412fc581085 100644 --- a/src/compiler/factory/nodeFactory.ts +++ b/src/compiler/factory/nodeFactory.ts @@ -998,6 +998,8 @@ namespace ts { case SyntaxKind.BigIntKeyword: case SyntaxKind.NeverKeyword: case SyntaxKind.ObjectKeyword: + case SyntaxKind.InKeyword: + case SyntaxKind.OutKeyword: case SyntaxKind.OverrideKeyword: case SyntaxKind.StringKeyword: case SyntaxKind.BooleanKeyword: @@ -1077,6 +1079,8 @@ namespace ts { if (flags & ModifierFlags.Override) result.push(createModifier(SyntaxKind.OverrideKeyword)); if (flags & ModifierFlags.Readonly) result.push(createModifier(SyntaxKind.ReadonlyKeyword)); if (flags & ModifierFlags.Async) result.push(createModifier(SyntaxKind.AsyncKeyword)); + if (flags & ModifierFlags.In) result.push(createModifier(SyntaxKind.InKeyword)); + if (flags & ModifierFlags.Out) result.push(createModifier(SyntaxKind.OutKeyword)); return result.length ? result : undefined; } @@ -1126,11 +1130,27 @@ namespace ts { // // @api - function createTypeParameterDeclaration(name: string | Identifier, constraint?: TypeNode, defaultType?: TypeNode) { + function createTypeParameterDeclaration(modifiers: readonly Modifier[] | undefined, name: string | Identifier, constraint?: TypeNode, defaultType?: TypeNode): TypeParameterDeclaration; + /** @deprecated */ + function createTypeParameterDeclaration(name: string | Identifier, constraint?: TypeNode, defaultType?: TypeNode): TypeParameterDeclaration; + function createTypeParameterDeclaration(modifiersOrName: readonly Modifier[] | string | Identifier | undefined , nameOrConstraint?: string | Identifier | TypeNode, constraintOrDefault?: TypeNode, defaultType?: TypeNode) { + let name; + let modifiers; + let constraint; + if (modifiersOrName === undefined || isArray(modifiersOrName)) { + modifiers = modifiersOrName; + name = nameOrConstraint as string | Identifier; + constraint = constraintOrDefault; + } + else { + modifiers = undefined; + name = modifiersOrName; + constraint = nameOrConstraint as TypeNode | undefined; + } const node = createBaseNamedDeclaration( SyntaxKind.TypeParameter, /*decorators*/ undefined, - /*modifiers*/ undefined, + modifiers, name ); node.constraint = constraint; @@ -1140,11 +1160,28 @@ namespace ts { } // @api - function updateTypeParameterDeclaration(node: TypeParameterDeclaration, name: Identifier, constraint: TypeNode | undefined, defaultType: TypeNode | undefined) { - return node.name !== name + function updateTypeParameterDeclaration(node: TypeParameterDeclaration, modifiers: readonly Modifier[] | undefined, name: Identifier, constraint: TypeNode | undefined, defaultType: TypeNode | undefined): TypeParameterDeclaration; + /** @deprecated */ + function updateTypeParameterDeclaration(node: TypeParameterDeclaration, name: Identifier, constraint: TypeNode | undefined, defaultType: TypeNode | undefined): TypeParameterDeclaration; + function updateTypeParameterDeclaration(node: TypeParameterDeclaration, modifiersOrName: readonly Modifier[] | Identifier | undefined, nameOrConstraint: Identifier | TypeNode | undefined, constraintOrDefault: TypeNode | undefined, defaultType?: TypeNode | undefined) { + let name; + let modifiers; + let constraint; + if (modifiersOrName === undefined || isArray(modifiersOrName)) { + modifiers = modifiersOrName; + name = nameOrConstraint as Identifier; + constraint = constraintOrDefault; + } + else { + modifiers = undefined; + name = modifiersOrName; + constraint = nameOrConstraint as TypeNode | undefined; + } + return node.modifiers !== modifiers + || node.name !== name || node.constraint !== constraint || node.default !== defaultType - ? update(createTypeParameterDeclaration(name, constraint, defaultType), node) + ? update(createTypeParameterDeclaration(modifiers, name, constraint, defaultType), node) : node; } diff --git a/src/compiler/parser.ts b/src/compiler/parser.ts index 69e9ada739c..5f9c7f0085e 100644 --- a/src/compiler/parser.ts +++ b/src/compiler/parser.ts @@ -117,7 +117,8 @@ namespace ts { return visitNode(cbNode, (node as QualifiedName).left) || visitNode(cbNode, (node as QualifiedName).right); case SyntaxKind.TypeParameter: - return visitNode(cbNode, (node as TypeParameterDeclaration).name) || + return visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, (node as TypeParameterDeclaration).name) || visitNode(cbNode, (node as TypeParameterDeclaration).constraint) || visitNode(cbNode, (node as TypeParameterDeclaration).default) || visitNode(cbNode, (node as TypeParameterDeclaration).expression); @@ -2176,7 +2177,7 @@ namespace ts { case ParsingContext.ArrayBindingElements: return token() === SyntaxKind.CommaToken || token() === SyntaxKind.DotDotDotToken || isBindingIdentifierOrPrivateIdentifierOrPattern(); case ParsingContext.TypeParameters: - return isIdentifier(); + return token() === SyntaxKind.InKeyword || isIdentifier(); case ParsingContext.ArrayLiteralMembers: switch (token()) { case SyntaxKind.CommaToken: @@ -3176,6 +3177,7 @@ namespace ts { function parseTypeParameter(): TypeParameterDeclaration { const pos = getNodePos(); + const modifiers = parseModifiers(); const name = parseIdentifier(); let constraint: TypeNode | undefined; let expression: Expression | undefined; @@ -3200,7 +3202,7 @@ namespace ts { } const defaultType = parseOptional(SyntaxKind.EqualsToken) ? parseType() : undefined; - const node = factory.createTypeParameterDeclaration(name, constraint, defaultType); + const node = factory.createTypeParameterDeclaration(modifiers, name, constraint, defaultType); node.expression = expression; return finishNode(node, pos); } @@ -3605,7 +3607,7 @@ namespace ts { const name = parseIdentifierName(); parseExpected(SyntaxKind.InKeyword); const type = parseType(); - return finishNode(factory.createTypeParameterDeclaration(name, type, /*defaultType*/ undefined), pos); + return finishNode(factory.createTypeParameterDeclaration(/*modifiers*/ undefined, name, type, /*defaultType*/ undefined), pos); } function parseMappedType() { @@ -3961,6 +3963,7 @@ namespace ts { const pos = getNodePos(); return finishNode( factory.createTypeParameterDeclaration( + /*modifiers*/ undefined, parseIdentifier(), /*constraint*/ undefined, /*defaultType*/ undefined @@ -8656,7 +8659,7 @@ namespace ts { if (nodeIsMissing(name)) { return undefined; } - return finishNode(factory.createTypeParameterDeclaration(name, /*constraint*/ undefined, defaultType), typeParameterPos); + return finishNode(factory.createTypeParameterDeclaration(/*modifiers*/ undefined, name, /*constraint*/ undefined, defaultType), typeParameterPos); } function parseTemplateTagTypeParameters() { diff --git a/src/compiler/program.ts b/src/compiler/program.ts index 31885ec7f12..a17654e981f 100644 --- a/src/compiler/program.ts +++ b/src/compiler/program.ts @@ -1025,8 +1025,7 @@ namespace ts { let files: SourceFile[]; let symlinks: SymlinkCache | undefined; let commonSourceDirectory: string; - let diagnosticsProducingTypeChecker: TypeChecker; - let noDiagnosticsTypeChecker: TypeChecker; + let typeChecker: TypeChecker; let classifiableNames: Set<__String>; const ambientModuleNameToUnmodifiedFileName = new Map(); let fileReasons = createMultiMap(); @@ -1304,21 +1303,19 @@ namespace ts { getProgramDiagnostics, getTypeChecker, getClassifiableNames, - getDiagnosticsProducingTypeChecker, getCommonSourceDirectory, emit, getCurrentDirectory: () => currentDirectory, - getNodeCount: () => getDiagnosticsProducingTypeChecker().getNodeCount(), - getIdentifierCount: () => getDiagnosticsProducingTypeChecker().getIdentifierCount(), - getSymbolCount: () => getDiagnosticsProducingTypeChecker().getSymbolCount(), - getTypeCount: () => getDiagnosticsProducingTypeChecker().getTypeCount(), - getInstantiationCount: () => getDiagnosticsProducingTypeChecker().getInstantiationCount(), - getRelationCacheSizes: () => getDiagnosticsProducingTypeChecker().getRelationCacheSizes(), + getNodeCount: () => getTypeChecker().getNodeCount(), + getIdentifierCount: () => getTypeChecker().getIdentifierCount(), + getSymbolCount: () => getTypeChecker().getSymbolCount(), + getTypeCount: () => getTypeChecker().getTypeCount(), + getInstantiationCount: () => getTypeChecker().getInstantiationCount(), + getRelationCacheSizes: () => getTypeChecker().getRelationCacheSizes(), getFileProcessingDiagnostics: () => fileProcessingDiagnostics, getResolvedTypeReferenceDirectives: () => resolvedTypeReferenceDirectives, isSourceFileFromExternalLibrary, isSourceFileDefaultLibrary, - dropDiagnosticsProducingTypeChecker, getSourceFileFromReference, getLibFileFromReference, sourceFileToPackageName, @@ -1980,16 +1977,8 @@ namespace ts { } } - function getDiagnosticsProducingTypeChecker() { - return diagnosticsProducingTypeChecker || (diagnosticsProducingTypeChecker = createTypeChecker(program, /*produceDiagnostics:*/ true)); - } - - function dropDiagnosticsProducingTypeChecker() { - diagnosticsProducingTypeChecker = undefined!; - } - function getTypeChecker() { - return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = createTypeChecker(program, /*produceDiagnostics:*/ false)); + return typeChecker || (typeChecker = createTypeChecker(program)); } function emit(sourceFile?: SourceFile, writeFileCallback?: WriteFileCallback, cancellationToken?: CancellationToken, emitOnlyDtsFiles?: boolean, transformers?: CustomTransformers, forceDtsEmit?: boolean): EmitResult { @@ -2017,7 +2006,7 @@ namespace ts { // This is because in the -out scenario all files need to be emitted, and therefore all // files need to be type checked. And the way to specify that all files need to be type // checked is to not pass the file to getEmitResolver. - const emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver(outFile(options) ? undefined : sourceFile, cancellationToken); + const emitResolver = getTypeChecker().getEmitResolver(outFile(options) ? undefined : sourceFile, cancellationToken); performance.mark("beforeEmit"); @@ -2121,15 +2110,7 @@ namespace ts { if (e instanceof OperationCanceledException) { // We were canceled while performing the operation. Because our type checker // might be a bad state, we need to throw it away. - // - // Note: we are overly aggressive here. We do not actually *have* to throw away - // the "noDiagnosticsTypeChecker". However, for simplicity, i'd like to keep - // the lifetimes of these two TypeCheckers the same. Also, we generally only - // cancel when the user has made a change anyways. And, in that case, we (the - // program instance) will get thrown away anyways. So trying to keep one of - // these type checkers alive doesn't serve much purpose. - noDiagnosticsTypeChecker = undefined!; - diagnosticsProducingTypeChecker = undefined!; + typeChecker = undefined!; } throw e; @@ -2153,7 +2134,7 @@ namespace ts { return emptyArray; } - const typeChecker = getDiagnosticsProducingTypeChecker(); + const typeChecker = getTypeChecker(); Debug.assert(!!sourceFile.bindDiagnostics); @@ -2209,7 +2190,7 @@ namespace ts { function getSuggestionDiagnostics(sourceFile: SourceFile, cancellationToken: CancellationToken): readonly DiagnosticWithLocation[] { return runWithCancellationToken(() => { - return getDiagnosticsProducingTypeChecker().getSuggestionDiagnostics(sourceFile, cancellationToken); + return getTypeChecker().getSuggestionDiagnostics(sourceFile, cancellationToken); }); } @@ -2292,6 +2273,13 @@ namespace ts { return "skip"; } break; + case SyntaxKind.ImportSpecifier: + case SyntaxKind.ExportSpecifier: + if ((node as ImportOrExportSpecifier).isTypeOnly) { + diagnostics.push(createDiagnosticForNode(node, Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, isImportSpecifier(node) ? "import...type" : "export...type")); + return "skip"; + } + break; case SyntaxKind.ImportEqualsDeclaration: diagnostics.push(createDiagnosticForNode(node, Diagnostics.import_can_only_be_used_in_TypeScript_files)); return "skip"; @@ -2414,6 +2402,8 @@ namespace ts { case SyntaxKind.DeclareKeyword: case SyntaxKind.AbstractKeyword: case SyntaxKind.OverrideKeyword: + case SyntaxKind.InKeyword: + case SyntaxKind.OutKeyword: diagnostics.push(createDiagnosticForNode(modifier, Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, tokenToString(modifier.kind))); break; @@ -2444,7 +2434,7 @@ namespace ts { function getDeclarationDiagnosticsForFileNoCache(sourceFile: SourceFile | undefined, cancellationToken: CancellationToken | undefined): readonly DiagnosticWithLocation[] { return runWithCancellationToken(() => { - const resolver = getDiagnosticsProducingTypeChecker().getEmitResolver(sourceFile, cancellationToken); + const resolver = getTypeChecker().getEmitResolver(sourceFile, cancellationToken); // Don't actually write any files since we're just getting diagnostics. return ts.getDeclarationDiagnostics(getEmitHost(noop), resolver, sourceFile) || emptyArray; }); @@ -2495,7 +2485,7 @@ namespace ts { } function getGlobalDiagnostics(): SortedReadonlyArray { - return rootNames.length ? sortAndDeduplicateDiagnostics(getDiagnosticsProducingTypeChecker().getGlobalDiagnostics().slice()) : emptyArray as any as SortedReadonlyArray; + return rootNames.length ? sortAndDeduplicateDiagnostics(getTypeChecker().getGlobalDiagnostics().slice()) : emptyArray as any as SortedReadonlyArray; } function getConfigFileParsingDiagnostics(): readonly Diagnostic[] { diff --git a/src/compiler/scanner.ts b/src/compiler/scanner.ts index 6cac0cb1936..107ff3a143e 100644 --- a/src/compiler/scanner.ts +++ b/src/compiler/scanner.ts @@ -131,6 +131,7 @@ namespace ts { protected: SyntaxKind.ProtectedKeyword, public: SyntaxKind.PublicKeyword, override: SyntaxKind.OverrideKeyword, + out: SyntaxKind.OutKeyword, readonly: SyntaxKind.ReadonlyKeyword, require: SyntaxKind.RequireKeyword, global: SyntaxKind.GlobalKeyword, diff --git a/src/compiler/transformers/declarations.ts b/src/compiler/transformers/declarations.ts index eae56dbaf1a..bfbd4d44712 100644 --- a/src/compiler/transformers/declarations.ts +++ b/src/compiler/transformers/declarations.ts @@ -1029,7 +1029,7 @@ namespace ts { } case SyntaxKind.TypeParameter: { if (isPrivateMethodTypeParameter(input) && (input.default || input.constraint)) { - return cleanup(factory.updateTypeParameterDeclaration(input, input.name, /*constraint*/ undefined, /*defaultType*/ undefined)); + return cleanup(factory.updateTypeParameterDeclaration(input, input.modifiers, input.name, /*constraint*/ undefined, /*defaultType*/ undefined)); } return cleanup(visitEachChild(input, visitDeclarationSubtree, context)); } diff --git a/src/compiler/transformers/ts.ts b/src/compiler/transformers/ts.ts index 85d600ec4dd..994601a4265 100644 --- a/src/compiler/transformers/ts.ts +++ b/src/compiler/transformers/ts.ts @@ -373,6 +373,8 @@ namespace ts { case SyntaxKind.ConstKeyword: case SyntaxKind.DeclareKeyword: case SyntaxKind.ReadonlyKeyword: + case SyntaxKind.InKeyword: + case SyntaxKind.OutKeyword: // TypeScript accessibility and readonly modifiers are elided // falls through case SyntaxKind.ArrayType: diff --git a/src/compiler/types.ts b/src/compiler/types.ts index 3fee2e6eac4..1046c79dd3a 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -176,6 +176,7 @@ namespace ts { ModuleKeyword, NamespaceKeyword, NeverKeyword, + OutKeyword, ReadonlyKeyword, RequireKeyword, NumberKeyword, @@ -602,6 +603,7 @@ namespace ts { | SyntaxKind.ProtectedKeyword | SyntaxKind.PublicKeyword | SyntaxKind.ReadonlyKeyword + | SyntaxKind.OutKeyword | SyntaxKind.OverrideKeyword | SyntaxKind.RequireKeyword | SyntaxKind.ReturnKeyword @@ -634,10 +636,12 @@ namespace ts { | SyntaxKind.DeclareKeyword | SyntaxKind.DefaultKeyword | SyntaxKind.ExportKeyword + | SyntaxKind.InKeyword | SyntaxKind.PrivateKeyword | SyntaxKind.ProtectedKeyword | SyntaxKind.PublicKeyword | SyntaxKind.ReadonlyKeyword + | SyntaxKind.OutKeyword | SyntaxKind.OverrideKeyword | SyntaxKind.StaticKeyword ; @@ -817,6 +821,8 @@ namespace ts { Deprecated = 1 << 13, // Deprecated tag. Override = 1 << 14, // Override method. + In = 1 << 15, // Contravariance modifier + Out = 1 << 16, // Covariance modifier HasComputedFlags = 1 << 29, // Modifier flags have been computed AccessibilityModifier = Public | Private | Protected, @@ -824,9 +830,9 @@ namespace ts { ParameterPropertyModifier = AccessibilityModifier | Readonly | Override, NonPublicAccessibilityModifier = Private | Protected, - TypeScriptModifier = Ambient | Public | Private | Protected | Readonly | Abstract | Const | Override, + TypeScriptModifier = Ambient | Public | Private | Protected | Readonly | Abstract | Const | Override | In | Out, ExportDefault = Export | Default, - All = Export | Ambient | Public | Private | Protected | Static | Readonly | Abstract | Async | Default | Const | Deprecated | Override + All = Export | Ambient | Public | Private | Protected | Static | Readonly | Abstract | Async | Default | Const | Deprecated | Override | In | Out } export const enum JsxFlags { @@ -1066,10 +1072,12 @@ namespace ts { export type DeclareKeyword = ModifierToken; export type DefaultKeyword = ModifierToken; export type ExportKeyword = ModifierToken; + export type InKeyword = ModifierToken; export type PrivateKeyword = ModifierToken; export type ProtectedKeyword = ModifierToken; export type PublicKeyword = ModifierToken; export type ReadonlyKeyword = ModifierToken; + export type OutKeyword = ModifierToken; export type OverrideKeyword = ModifierToken; export type StaticKeyword = ModifierToken; @@ -1083,9 +1091,11 @@ namespace ts { | DeclareKeyword | DefaultKeyword | ExportKeyword + | InKeyword | PrivateKeyword | ProtectedKeyword | PublicKeyword + | OutKeyword | OverrideKeyword | ReadonlyKeyword | StaticKeyword @@ -4006,11 +4016,6 @@ namespace ts { /* @internal */ getCommonSourceDirectory(): string; - // For testing purposes only. Should not be used by any other consumers (including the - // language service). - /* @internal */ getDiagnosticsProducingTypeChecker(): TypeChecker; - /* @internal */ dropDiagnosticsProducingTypeChecker(): void; - /* @internal */ getCachedSemanticDiagnostics(sourceFile?: SourceFile): readonly Diagnostic[] | undefined; /* @internal */ getClassifiableNames(): Set<__String>; @@ -5244,7 +5249,6 @@ namespace ts { pattern?: DestructuringPattern; // Destructuring pattern represented by type (if any) aliasSymbol?: Symbol; // Alias associated with type aliasTypeArguments?: readonly Type[]; // Alias type arguments (if any) - /* @internal */ aliasTypeArgumentsContainsMarker?: boolean; // Alias type arguments (if any) /* @internal */ permissiveInstantiation?: Type; // Instantiation with type parameters mapped to wildcard type /* @internal */ @@ -5325,22 +5329,21 @@ namespace ts { ObjectLiteralPatternWithComputedProperties = 1 << 9, // Object literal pattern with computed properties ReverseMapped = 1 << 10, // Object contains a property from a reverse-mapped type JsxAttributes = 1 << 11, // Jsx attributes type - MarkerType = 1 << 12, // Marker type used for variance probing - JSLiteral = 1 << 13, // Object type declared in JS - disables errors on read/write of nonexisting members - FreshLiteral = 1 << 14, // Fresh object literal - ArrayLiteral = 1 << 15, // Originates in an array literal + JSLiteral = 1 << 12, // Object type declared in JS - disables errors on read/write of nonexisting members + FreshLiteral = 1 << 13, // Fresh object literal + ArrayLiteral = 1 << 14, // Originates in an array literal /* @internal */ - PrimitiveUnion = 1 << 16, // Union of only primitive types + PrimitiveUnion = 1 << 15, // Union of only primitive types /* @internal */ - ContainsWideningType = 1 << 17, // Type is or contains undefined or null widening type + ContainsWideningType = 1 << 16, // Type is or contains undefined or null widening type /* @internal */ - ContainsObjectOrArrayLiteral = 1 << 18, // Type is or contains object literal type + ContainsObjectOrArrayLiteral = 1 << 17, // Type is or contains object literal type /* @internal */ - NonInferrableType = 1 << 19, // Type is or contains anyFunctionType or silentNeverType + NonInferrableType = 1 << 18, // Type is or contains anyFunctionType or silentNeverType /* @internal */ - CouldContainTypeVariablesComputed = 1 << 20, // CouldContainTypeVariables flag has been computed + CouldContainTypeVariablesComputed = 1 << 19, // CouldContainTypeVariables flag has been computed /* @internal */ - CouldContainTypeVariables = 1 << 21, // Type could contain a type variable + CouldContainTypeVariables = 1 << 20, // Type could contain a type variable ClassOrInterface = Class | Interface, /* @internal */ @@ -5352,36 +5355,36 @@ namespace ts { ObjectTypeKindMask = ClassOrInterface | Reference | Tuple | Anonymous | Mapped | ReverseMapped | EvolvingArray, // Flags that require TypeFlags.Object - ContainsSpread = 1 << 22, // Object literal contains spread operation - ObjectRestType = 1 << 23, // Originates in object rest declaration - InstantiationExpressionType = 1 << 24, // Originates in instantiation expression + ContainsSpread = 1 << 21, // Object literal contains spread operation + ObjectRestType = 1 << 22, // Originates in object rest declaration + InstantiationExpressionType = 1 << 23, // Originates in instantiation expression /* @internal */ - IsClassInstanceClone = 1 << 25, // Type is a clone of a class instance type + IsClassInstanceClone = 1 << 24, // Type is a clone of a class instance type // Flags that require TypeFlags.Object and ObjectFlags.Reference /* @internal */ - IdenticalBaseTypeCalculated = 1 << 26, // has had `getSingleBaseForNonAugmentingSubtype` invoked on it already + IdenticalBaseTypeCalculated = 1 << 25, // has had `getSingleBaseForNonAugmentingSubtype` invoked on it already /* @internal */ - IdenticalBaseTypeExists = 1 << 27, // has a defined cachedEquivalentBaseType member + IdenticalBaseTypeExists = 1 << 26, // has a defined cachedEquivalentBaseType member // Flags that require TypeFlags.UnionOrIntersection or TypeFlags.Substitution /* @internal */ - IsGenericTypeComputed = 1 << 22, // IsGenericObjectType flag has been computed + IsGenericTypeComputed = 1 << 21, // IsGenericObjectType flag has been computed /* @internal */ - IsGenericObjectType = 1 << 23, // Union or intersection contains generic object type + IsGenericObjectType = 1 << 22, // Union or intersection contains generic object type /* @internal */ - IsGenericIndexType = 1 << 24, // Union or intersection contains generic index type + IsGenericIndexType = 1 << 23, // Union or intersection contains generic index type /* @internal */ IsGenericType = IsGenericObjectType | IsGenericIndexType, // Flags that require TypeFlags.Union /* @internal */ - ContainsIntersections = 1 << 25, // Union contains intersections + ContainsIntersections = 1 << 24, // Union contains intersections // Flags that require TypeFlags.Intersection /* @internal */ - IsNeverIntersectionComputed = 1 << 25, // IsNeverLike flag has been computed + IsNeverIntersectionComputed = 1 << 24, // IsNeverLike flag has been computed /* @internal */ - IsNeverIntersection = 1 << 26, // Intersection reduces to never + IsNeverIntersection = 1 << 25, // Intersection reduces to never } /* @internal */ @@ -7240,7 +7243,11 @@ namespace ts { // Signature elements // + createTypeParameterDeclaration(modifiers: readonly Modifier[] | undefined, name: string | Identifier, constraint?: TypeNode, defaultType?: TypeNode): TypeParameterDeclaration; + /** @deprecated */ createTypeParameterDeclaration(name: string | Identifier, constraint?: TypeNode, defaultType?: TypeNode): TypeParameterDeclaration; + updateTypeParameterDeclaration(node: TypeParameterDeclaration, modifiers: readonly Modifier[] | undefined, name: Identifier, constraint: TypeNode | undefined, defaultType: TypeNode | undefined): TypeParameterDeclaration; + /** @deprecated */ updateTypeParameterDeclaration(node: TypeParameterDeclaration, name: Identifier, constraint: TypeNode | undefined, defaultType: TypeNode | undefined): TypeParameterDeclaration; createParameterDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, dotDotDotToken: DotDotDotToken | undefined, name: string | BindingName, questionToken?: QuestionToken, type?: TypeNode, initializer?: Expression): ParameterDeclaration; updateParameterDeclaration(node: ParameterDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, dotDotDotToken: DotDotDotToken | undefined, name: string | BindingName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): ParameterDeclaration; diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index 3366b214d09..2465c336345 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -5003,6 +5003,8 @@ namespace ts { case SyntaxKind.AsyncKeyword: return ModifierFlags.Async; case SyntaxKind.ReadonlyKeyword: return ModifierFlags.Readonly; case SyntaxKind.OverrideKeyword: return ModifierFlags.Override; + case SyntaxKind.InKeyword: return ModifierFlags.In; + case SyntaxKind.OutKeyword: return ModifierFlags.Out; } return ModifierFlags.None; } diff --git a/src/compiler/utilitiesPublic.ts b/src/compiler/utilitiesPublic.ts index e3571024cc1..ecfb4e52daf 100644 --- a/src/compiler/utilitiesPublic.ts +++ b/src/compiler/utilitiesPublic.ts @@ -1187,11 +1187,13 @@ namespace ts { case SyntaxKind.DeclareKeyword: case SyntaxKind.DefaultKeyword: case SyntaxKind.ExportKeyword: + case SyntaxKind.InKeyword: case SyntaxKind.PublicKeyword: case SyntaxKind.PrivateKeyword: case SyntaxKind.ProtectedKeyword: case SyntaxKind.ReadonlyKeyword: case SyntaxKind.StaticKeyword: + case SyntaxKind.OutKeyword: case SyntaxKind.OverrideKeyword: return true; } @@ -1333,7 +1335,9 @@ namespace ts { || kind === SyntaxKind.CallSignature || kind === SyntaxKind.PropertySignature || kind === SyntaxKind.MethodSignature - || kind === SyntaxKind.IndexSignature; + || kind === SyntaxKind.IndexSignature + || kind === SyntaxKind.GetAccessor + || kind === SyntaxKind.SetAccessor; } export function isClassOrTypeElement(node: Node): node is ClassElement | TypeElement { diff --git a/src/compiler/visitorPublic.ts b/src/compiler/visitorPublic.ts index 75aa702ff8a..ef05168148e 100644 --- a/src/compiler/visitorPublic.ts +++ b/src/compiler/visitorPublic.ts @@ -385,6 +385,7 @@ namespace ts { case SyntaxKind.TypeParameter: Debug.type(node); return factory.updateTypeParameterDeclaration(node, + nodesVisitor(node.modifiers, visitor, isModifier), nodeVisitor(node.name, visitor, isIdentifier), nodeVisitor(node.constraint, visitor, isTypeNode), nodeVisitor(node.default, visitor, isTypeNode)); diff --git a/src/harness/harnessGlobals.ts b/src/harness/harnessGlobals.ts index 1a2db1415b6..79acccf26ce 100644 --- a/src/harness/harnessGlobals.ts +++ b/src/harness/harnessGlobals.ts @@ -20,8 +20,8 @@ globalThis.assert = _chai.assert; } assertDeepImpl(a, b, msg); - function arrayExtraKeysObject(a: readonly ({} | null | undefined)[]): object { - const obj: { [key: string]: {} | null | undefined } = {}; + function arrayExtraKeysObject(a: readonly unknown[]): object { + const obj: { [key: string]: unknown } = {}; for (const key in a) { if (Number.isNaN(Number(key))) { obj[key] = a[key]; diff --git a/src/harness/harnessIO.ts b/src/harness/harnessIO.ts index 99da90f44c3..558aca6bfd3 100644 --- a/src/harness/harnessIO.ts +++ b/src/harness/harnessIO.ts @@ -717,7 +717,7 @@ namespace Harness { // These types are equivalent, but depend on what order the compiler observed // certain parts of the program. - const fullWalker = new TypeWriterWalker(program, /*fullTypeCheck*/ true, !!hasErrorBaseline); + const fullWalker = new TypeWriterWalker(program, !!hasErrorBaseline); // Produce baselines. The first gives the types for all expressions. // The second gives symbols for all identifiers. diff --git a/src/harness/harnessLanguageService.ts b/src/harness/harnessLanguageService.ts index be17bbdef0e..5468068d922 100644 --- a/src/harness/harnessLanguageService.ts +++ b/src/harness/harnessLanguageService.ts @@ -994,7 +994,7 @@ namespace Harness.LanguageService { cancellationToken: ts.server.nullCancellationToken, useSingleInferredProject: false, useInferredProjectPerProjectRoot: false, - typingsInstaller: undefined!, // TODO: GH#18217 + typingsInstaller: { ...ts.server.nullTypingsInstaller, globalTypingsCacheLocation: "/Library/Caches/typescript" }, byteLength: Utils.byteLength, hrtime: process.hrtime, logger: serverHost, diff --git a/src/harness/typeWriter.ts b/src/harness/typeWriter.ts index e7f8e8d28b1..3de4f3962e6 100644 --- a/src/harness/typeWriter.ts +++ b/src/harness/typeWriter.ts @@ -41,12 +41,10 @@ namespace Harness { private checker: ts.TypeChecker; - constructor(private program: ts.Program, fullTypeCheck: boolean, private hadErrorBaseline: boolean) { + constructor(private program: ts.Program, private hadErrorBaseline: boolean) { // Consider getting both the diagnostics checker and the non-diagnostics checker to verify // they are consistent. - this.checker = fullTypeCheck - ? program.getDiagnosticsProducingTypeChecker() - : program.getTypeChecker(); + this.checker = program.getTypeChecker(); } public *getSymbols(fileName: string): IterableIterator { diff --git a/src/lib/es2020.intl.d.ts b/src/lib/es2020.intl.d.ts index 581e9fb15cd..c7d4d725368 100644 --- a/src/lib/es2020.intl.d.ts +++ b/src/lib/es2020.intl.d.ts @@ -291,12 +291,34 @@ declare namespace Intl { new (tag: BCP47LanguageTag | Locale, options?: LocaleOptions): Locale; }; - interface DisplayNamesOptions { - locale: UnicodeBCP47LocaleIdentifier; + type DisplayNamesFallback = + | "code" + | "none"; + + type ResolvedDisplayNamesType = + | "language" + | "region" + | "script" + | "currency"; + + type DisplayNamesType = + | ResolvedDisplayNamesType + | "calendar" + | "datetimeField"; + + interface DisplayNamesOptions { localeMatcher: RelativeTimeFormatLocaleMatcher; style: RelativeTimeFormatStyle; - type: "language" | "region" | "script" | "currency"; - fallback: "code" | "none"; + type: DisplayNamesType; + languageDisplay: "dialect" | "standard"; + fallback: DisplayNamesFallback; + } + + interface ResolvedDisplayNamesOptions { + locale: UnicodeBCP47LocaleIdentifier; + style: RelativeTimeFormatStyle; + type: ResolvedDisplayNamesType; + fallback: DisplayNamesFallback; } interface DisplayNames { @@ -322,7 +344,7 @@ declare namespace Intl { * * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DisplayNames/resolvedOptions). */ - resolvedOptions(): DisplayNamesOptions; + resolvedOptions(): ResolvedDisplayNamesOptions; } /** diff --git a/src/loc/lcl/chs/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/chs/diagnosticMessages/diagnosticMessages.generated.json.lcl index 87a20df8f82..eb8e85488ff 100644 --- a/src/loc/lcl/chs/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/chs/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -963,6 +963,15 @@ + + + + + + + + + @@ -1421,10 +1430,13 @@ - + + + + @@ -1568,10 +1580,13 @@ - + + + + @@ -2462,10 +2477,13 @@ - + - + + + + @@ -3383,10 +3401,13 @@ - + + + + @@ -3879,6 +3900,15 @@ + + + + + + + + + @@ -4605,6 +4635,15 @@ + + + + + + + + + @@ -4670,10 +4709,13 @@ - + - + + + + @@ -4715,10 +4757,13 @@ - + + + + @@ -4844,10 +4889,13 @@ - + - + + + + @@ -4871,10 +4919,13 @@ - + + + + @@ -4898,10 +4949,13 @@ - + + + + @@ -4925,10 +4979,13 @@ - + - + + + + @@ -5006,10 +5063,13 @@ - + - + + + + @@ -5024,10 +5084,13 @@ - `s from expanding the number of files TypeScript should add to a project.]]> + 's from expanding the number of files TypeScript should add to a project.]]> - ” 扩展 TypeScript 应添加到项目的文件数。]]> + ” 扩展 TypeScript 应添加到项目的文件数。]]> + + `s from expanding the number of files TypeScript should add to a project.]]> + @@ -5435,10 +5498,13 @@ - + - + + + + @@ -5489,10 +5555,13 @@ - + - + + + + @@ -5516,10 +5585,13 @@ - + + + + @@ -5541,21 +5613,24 @@ - + - + - + - + - + + + + @@ -5570,19 +5645,13 @@ - + - - - - - - - - - - + + + + @@ -5660,10 +5729,13 @@ - + - + + + + @@ -5696,10 +5768,13 @@ - + - + + + + @@ -6980,10 +7055,13 @@ - + - + + + + @@ -7416,15 +7494,6 @@ - - - - - - - - - @@ -8124,15 +8193,6 @@ - - - - - - - - - @@ -8183,10 +8243,13 @@ - + + + + @@ -10595,10 +10658,13 @@ - + - + + + + @@ -11813,10 +11879,13 @@ - + + + + @@ -11876,10 +11945,13 @@ - + - + + + + @@ -11948,19 +12020,25 @@ - + + + + - + - + + + + @@ -12038,10 +12116,13 @@ - + - + + + + @@ -12072,15 +12153,6 @@ - - - - - - - - - @@ -12101,10 +12173,13 @@ - + + + + @@ -12122,10 +12197,13 @@ - + - + + + + @@ -12138,6 +12216,15 @@ + + + + + + + + + @@ -12404,10 +12491,13 @@ - + - + + + + @@ -13026,11 +13116,11 @@ - + - + - + @@ -13623,6 +13713,15 @@ + + + + + + + + + @@ -13914,6 +14013,15 @@ + + + + + + + + + @@ -14127,15 +14235,6 @@ - - - - - - - - - @@ -15050,10 +15149,13 @@ - + + + + @@ -15528,6 +15630,15 @@ + + + + + + + + + @@ -15564,6 +15675,15 @@ + + + + + + + + + @@ -15804,6 +15924,15 @@ + + + + + + + + + diff --git a/src/loc/lcl/cht/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/cht/diagnosticMessages/diagnosticMessages.generated.json.lcl index 185797d3068..854c998d309 100644 --- a/src/loc/lcl/cht/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/cht/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -963,6 +963,15 @@ + + + + + + + + + @@ -1421,10 +1430,13 @@ - + - + + + + @@ -1568,10 +1580,13 @@ - + - + + + + @@ -2462,10 +2477,13 @@ - + - + + + + @@ -3383,10 +3401,13 @@ - + - + + + + @@ -3879,6 +3900,15 @@ + + + + + + + + + @@ -4605,6 +4635,15 @@ + + + + + + + + + @@ -4670,10 +4709,13 @@ - + - + + + + @@ -4715,10 +4757,13 @@ - + - + + + + @@ -4844,10 +4889,13 @@ - + - + + + + @@ -4871,10 +4919,13 @@ - + - + + + + @@ -4898,10 +4949,13 @@ - + - + + + + @@ -4925,10 +4979,13 @@ - + - + + + + @@ -5006,10 +5063,13 @@ - + - + + + + @@ -5024,10 +5084,13 @@ - `s from expanding the number of files TypeScript should add to a project.]]> + 's from expanding the number of files TypeScript should add to a project.]]> - ` 擴充 TypeScript 應該加入專案的檔案數目。]]> + ' 擴充 TypeScript 應該加入專案的檔案數目。]]> + + `s from expanding the number of files TypeScript should add to a project.]]> + @@ -5435,10 +5498,13 @@ - + - + + + + @@ -5489,10 +5555,13 @@ - + - + + + + @@ -5516,10 +5585,13 @@ - + - + + + + @@ -5541,9 +5613,9 @@ - + - + @@ -5552,10 +5624,13 @@ - + - + + + + @@ -5570,19 +5645,13 @@ - + - - - - - - - - - - + + + + @@ -5660,10 +5729,13 @@ - + - + + + + @@ -5696,10 +5768,13 @@ - + - + + + + @@ -6980,10 +7055,13 @@ - + - + + + + @@ -7416,15 +7494,6 @@ - - - - - - - - - @@ -8124,15 +8193,6 @@ - - - - - - - - - @@ -8183,10 +8243,13 @@ - + - + + + + @@ -10595,10 +10658,13 @@ - + - + + + + @@ -11813,10 +11879,13 @@ - + - + + + + @@ -11876,10 +11945,13 @@ - + - + + + + @@ -11948,19 +12020,25 @@ - + - + + + + - + - + + + + @@ -12038,10 +12116,13 @@ - + - + + + + @@ -12072,15 +12153,6 @@ - - - - - - - - - @@ -12101,10 +12173,13 @@ - + - + + + + @@ -12122,10 +12197,13 @@ - + - + + + + @@ -12138,6 +12216,15 @@ + + + + + + + + + @@ -12404,10 +12491,13 @@ - + - + + + + @@ -13026,11 +13116,11 @@ - + - + - + @@ -13623,6 +13713,15 @@ + + + + + + + + + @@ -13914,6 +14013,15 @@ + + + + + + + + + @@ -14127,15 +14235,6 @@ - - - - - - - - - @@ -15050,10 +15149,13 @@ - + - + + + + @@ -15528,6 +15630,15 @@ + + + + + + + + + @@ -15564,6 +15675,15 @@ + + + + + + + + + @@ -15804,6 +15924,15 @@ + + + + + + + + + diff --git a/src/loc/lcl/csy/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/csy/diagnosticMessages/diagnosticMessages.generated.json.lcl index 51958921084..de7316b3cb6 100644 --- a/src/loc/lcl/csy/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/csy/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -972,6 +972,15 @@ + + + + + + + + + @@ -1430,10 +1439,13 @@ - + - + + + + @@ -1577,10 +1589,13 @@ - + - + + + + @@ -2471,10 +2486,13 @@ - + - + + + + @@ -3392,10 +3410,13 @@ - + - + + + + @@ -3888,6 +3909,15 @@ + + + + + + + + + @@ -4614,6 +4644,15 @@ + + + + + + + + + @@ -4679,10 +4718,13 @@ - + - + + + + @@ -4724,10 +4766,13 @@ - + - + + + + @@ -4853,10 +4898,13 @@ - + - + + + + @@ -4880,10 +4928,13 @@ - + - + + + + @@ -4907,10 +4958,13 @@ - + - + + + + @@ -4934,10 +4988,13 @@ - + - + + + + @@ -5015,10 +5072,13 @@ - + - + + + + @@ -5033,10 +5093,13 @@ - `s from expanding the number of files TypeScript should add to a project.]]> + 's from expanding the number of files TypeScript should add to a project.]]> - + zvětšování počtu souborů, které by typeScript měl přidat do projektu.]]> + + `s from expanding the number of files TypeScript should add to a project.]]> + @@ -5444,10 +5507,13 @@ - + - + + + + @@ -5498,10 +5564,13 @@ - + + + + @@ -5525,10 +5594,13 @@ - + - + + + + @@ -5550,21 +5622,24 @@ - + - + - + - + - + + + + @@ -5579,19 +5654,13 @@ - + - - - - - - - - - - + + + + @@ -5669,10 +5738,13 @@ - + - + + + + @@ -5705,10 +5777,13 @@ - + - + + + + @@ -6989,10 +7064,13 @@ - + - + + + + @@ -7425,15 +7503,6 @@ - - - - - - - - - @@ -8133,15 +8202,6 @@ - - - - - - - - - @@ -8192,10 +8252,13 @@ - + - + + + + @@ -10604,10 +10667,13 @@ - + - + + + + @@ -11822,10 +11888,13 @@ - + - + + + + @@ -11885,10 +11954,13 @@ - + + + + @@ -11957,19 +12029,25 @@ - + - + + + + - + - + + + + @@ -12047,10 +12125,13 @@ - + - + + + + @@ -12081,15 +12162,6 @@ - - - - - - - - - @@ -12110,10 +12182,13 @@ - + - + + + + @@ -12131,10 +12206,13 @@ - + - + + + + @@ -12147,6 +12225,15 @@ + + + + + + + + + @@ -12413,10 +12500,13 @@ - + - + + + + @@ -13035,11 +13125,11 @@ - + - + - + @@ -13632,6 +13722,15 @@ + + + + + + + + + @@ -13923,6 +14022,15 @@ + + + + + + + + + @@ -14136,15 +14244,6 @@ - - - - - - - - - @@ -15059,10 +15158,13 @@ - + - + + + + @@ -15537,6 +15639,15 @@ + + + + + + + + + @@ -15573,6 +15684,15 @@ + + + + + + + + + @@ -15813,6 +15933,15 @@ + + + + + + + + + diff --git a/src/loc/lcl/deu/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/deu/diagnosticMessages/diagnosticMessages.generated.json.lcl index abd856b32b6..97ec28c5a0d 100644 --- a/src/loc/lcl/deu/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/deu/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -960,6 +960,15 @@ + + + + + + + + + @@ -1418,10 +1427,13 @@ - + - + + + + @@ -1565,10 +1577,13 @@ - + - + + + + @@ -2459,10 +2474,13 @@ - + - + + + + @@ -3380,10 +3398,13 @@ - + - + + + + @@ -3876,6 +3897,15 @@ + + + + + + + + + @@ -4602,6 +4632,15 @@ + + + + + + + + + @@ -4667,10 +4706,13 @@ - + - + + + + @@ -4712,10 +4754,13 @@ - + - + + + + @@ -4841,10 +4886,13 @@ - + - + + + + @@ -4868,10 +4916,13 @@ - + - + + + + @@ -4895,10 +4946,13 @@ - + - + + + + @@ -4922,10 +4976,13 @@ - + - + + + + @@ -5003,10 +5060,13 @@ - + + + + @@ -5021,10 +5081,13 @@ - `s from expanding the number of files TypeScript should add to a project.]]> + 's from expanding the number of files TypeScript should add to a project.]]> - " die Anzahl der Dateien erweitern, die TypeScript einem Projekt hinzufügen soll.]]> + “ die Anzahl der Dateien erweitern, die TypeScript einem Projekt hinzufügen soll.]]> + + `s from expanding the number of files TypeScript should add to a project.]]> + @@ -5432,10 +5495,13 @@ - + - + + + + @@ -5486,10 +5552,13 @@ - + - + + + + @@ -5513,10 +5582,13 @@ - + - + + + + @@ -5538,9 +5610,9 @@ - + - + @@ -5549,10 +5621,13 @@ - + - + + + + @@ -5567,19 +5642,13 @@ - + - - - - - - - - - - + + + + @@ -5657,10 +5726,13 @@ - + - + + + + @@ -5693,10 +5765,13 @@ - + - + + + + @@ -6977,10 +7052,13 @@ - + - + + + + @@ -7413,15 +7491,6 @@ - - - - - - - - - @@ -8121,15 +8190,6 @@ - - - - - - - - - @@ -8180,10 +8240,13 @@ - + - + + + + @@ -10589,10 +10652,13 @@ - + - + + + + @@ -11807,10 +11873,13 @@ - + - + + + + @@ -11870,10 +11939,13 @@ - + + + + @@ -11942,19 +12014,25 @@ - + - + + + + - + - + + + + @@ -12032,10 +12110,13 @@ - + - + + + + @@ -12066,15 +12147,6 @@ - - - - - - - - - @@ -12095,10 +12167,13 @@ - + - + + + + @@ -12116,10 +12191,13 @@ - + - + + + + @@ -12132,6 +12210,15 @@ + + + + + + + + + @@ -12398,10 +12485,13 @@ - + - + + + + @@ -13020,11 +13110,11 @@ - + - + - + @@ -13617,6 +13707,15 @@ + + + + + + + + + @@ -13908,6 +14007,15 @@ + + + + + + + + + @@ -14121,15 +14229,6 @@ - - - - - - - - - @@ -15044,10 +15143,13 @@ - + - + + + + @@ -15522,6 +15624,15 @@ + + + + + + + + + @@ -15558,6 +15669,15 @@ + + + + + + + + + @@ -15798,6 +15918,15 @@ + + + + + + + + + diff --git a/src/loc/lcl/esn/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/esn/diagnosticMessages/diagnosticMessages.generated.json.lcl index ef6878ab2e8..b534ce0a673 100644 --- a/src/loc/lcl/esn/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/esn/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -972,6 +972,15 @@ + + + + + + + + + @@ -1433,10 +1442,13 @@ - + - + + + + @@ -1580,10 +1592,13 @@ - + + + + @@ -2474,10 +2489,13 @@ - + - + + + + @@ -3395,10 +3413,13 @@ - + - + + + + @@ -3891,6 +3912,15 @@ + + + + + + + + + @@ -4617,6 +4647,15 @@ + + + + + + + + + @@ -4682,10 +4721,13 @@ - + - + + + + @@ -4727,10 +4769,13 @@ - + + + + @@ -4856,10 +4901,13 @@ - + + + + @@ -4883,10 +4931,13 @@ - + - + + + + @@ -4910,10 +4961,13 @@ - + - + + + + @@ -4937,10 +4991,13 @@ - + + + + @@ -5018,10 +5075,13 @@ - + - + + + + @@ -5036,10 +5096,13 @@ - `s from expanding the number of files TypeScript should add to a project.]]> + 's from expanding the number of files TypeScript should add to a project.]]> " amplíe el número de archivos que TypeScript debe agregar a un proyecto.]]> + + `s from expanding the number of files TypeScript should add to a project.]]> + @@ -5447,10 +5510,13 @@ - + + + + @@ -5501,10 +5567,13 @@ - + - + + + + @@ -5528,10 +5597,13 @@ - + - + + + + @@ -5553,9 +5625,9 @@ - + - + @@ -5564,10 +5636,13 @@ - + - + + + + @@ -5582,19 +5657,13 @@ - + - - - - - - - - - - + + + + @@ -5672,10 +5741,13 @@ - + - + + + + @@ -5708,10 +5780,13 @@ - + - + + + + @@ -6992,10 +7067,13 @@ - + - + + + + @@ -7428,15 +7506,6 @@ - - - - - - - - - @@ -8136,15 +8205,6 @@ - - - - - - - - - @@ -8195,10 +8255,13 @@ - + + + + @@ -10607,10 +10670,13 @@ - + - + + + + @@ -11825,10 +11891,13 @@ - + - + + + + @@ -11888,10 +11957,13 @@ - + - + + + + @@ -11960,19 +12032,25 @@ - + - + + + + - + + + + @@ -12050,10 +12128,13 @@ - + - + + + + @@ -12084,15 +12165,6 @@ - - - - - - - - - @@ -12113,10 +12185,13 @@ - + + + + @@ -12134,10 +12209,13 @@ - + - + + + + @@ -12150,6 +12228,15 @@ + + + + + + + + + @@ -12416,10 +12503,13 @@ - + - + + + + @@ -13038,11 +13128,11 @@ - + - + - + @@ -13635,6 +13725,15 @@ + + + + + + + + + @@ -13926,6 +14025,15 @@ + + + + + + + + + @@ -14139,15 +14247,6 @@ - - - - - - - - - @@ -15062,10 +15161,13 @@ - + - + + + + @@ -15540,6 +15642,15 @@ + + + + + + + + + @@ -15576,6 +15687,15 @@ + + + + + + + + + @@ -15816,6 +15936,15 @@ + + + + + + + + + diff --git a/src/loc/lcl/fra/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/fra/diagnosticMessages/diagnosticMessages.generated.json.lcl index ffddbac1710..d56a62f1057 100644 --- a/src/loc/lcl/fra/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/fra/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -972,6 +972,15 @@ + + + + + + + + + @@ -1433,10 +1442,13 @@ - + + + + @@ -1580,10 +1592,13 @@ - + + + + @@ -2474,10 +2489,13 @@ - + - + + + + @@ -3395,10 +3413,13 @@ - + + + + @@ -3891,6 +3912,15 @@ + + + + + + + + + @@ -4617,6 +4647,15 @@ + + + + + + + + + @@ -4682,10 +4721,13 @@ - + - + + + + @@ -4727,10 +4769,13 @@ - + + + + @@ -4856,10 +4901,13 @@ - + + + + @@ -4883,10 +4931,13 @@ - + + + + @@ -4910,10 +4961,13 @@ - + - + + + + @@ -4937,10 +4991,13 @@ - + - + + + + @@ -5018,10 +5075,13 @@ - + - + + + + @@ -5036,10 +5096,13 @@ - `s from expanding the number of files TypeScript should add to a project.]]> + 's from expanding the number of files TypeScript should add to a project.]]> » d’étendre le nombre de fichiers que TypeScript doit ajouter à un projet.]]> + + `s from expanding the number of files TypeScript should add to a project.]]> + @@ -5447,10 +5510,13 @@ - + + + + @@ -5501,10 +5567,13 @@ - + - + + + + @@ -5528,10 +5597,13 @@ - + + + + @@ -5553,21 +5625,24 @@ - + - + - + - + + + + @@ -5582,19 +5657,13 @@ - + - - - - - - - - - - + + + + @@ -5672,10 +5741,13 @@ - + - + + + + @@ -5708,10 +5780,13 @@ - + - + + + + @@ -6992,10 +7067,13 @@ - + + + + @@ -7428,15 +7506,6 @@ - - - - - - - - - @@ -8136,15 +8205,6 @@ - - - - - - - - - @@ -8195,10 +8255,13 @@ - + + + + @@ -10607,10 +10670,13 @@ - + - + + + + @@ -11825,10 +11891,13 @@ - + + + + @@ -11888,10 +11957,13 @@ - + - + + + + @@ -11960,19 +12032,25 @@ - + + + + - + + + + @@ -12050,10 +12128,13 @@ - + + + + @@ -12084,15 +12165,6 @@ - - - - - - - - - @@ -12113,10 +12185,13 @@ - + + + + @@ -12134,10 +12209,13 @@ - + + + + @@ -12150,6 +12228,15 @@ + + + + + + + + + @@ -12416,10 +12503,13 @@ - + + + + @@ -13038,11 +13128,11 @@ - + - + - + @@ -13635,6 +13725,15 @@ + + + + + + + + + @@ -13926,6 +14025,15 @@ + + + + + + + + + @@ -14139,15 +14247,6 @@ - - - - - - - - - @@ -15062,10 +15161,13 @@ - + + + + @@ -15540,6 +15642,15 @@ + + + + + + + + + @@ -15576,6 +15687,15 @@ + + + + + + + + + @@ -15816,6 +15936,15 @@ + + + + + + + + + diff --git a/src/loc/lcl/ita/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/ita/diagnosticMessages/diagnosticMessages.generated.json.lcl index 267f4b9398c..59951b9b449 100644 --- a/src/loc/lcl/ita/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/ita/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -963,6 +963,15 @@ + + + + + + + + + @@ -1421,10 +1430,13 @@ - + - + + + + @@ -1568,10 +1580,13 @@ - + - + + + + @@ -2462,10 +2477,13 @@ - + - + + + + @@ -3383,10 +3401,13 @@ - + - + + + + @@ -3879,6 +3900,15 @@ + + + + + + + + + @@ -4605,6 +4635,15 @@ + + + + + + + + + @@ -4670,10 +4709,13 @@ - + - + + + + @@ -4715,10 +4757,13 @@ - + - + + + + @@ -4844,10 +4889,13 @@ - + - + + + + @@ -4871,10 +4919,13 @@ - + - + + + + @@ -4898,10 +4949,13 @@ - + - + + + + @@ -4925,10 +4979,13 @@ - + - + + + + @@ -5006,10 +5063,13 @@ - + - + + + + @@ -5024,10 +5084,13 @@ - `s from expanding the number of files TypeScript should add to a project.]]> + 's from expanding the number of files TypeScript should add to a project.]]> - ` di espandere il numero di file che TypeScript deve aggiungere a un progetto.]]> + ' di espandere il numero di file che TypeScript deve aggiungere a un progetto.]]> + + `s from expanding the number of files TypeScript should add to a project.]]> + @@ -5435,10 +5498,13 @@ - + - + + + + @@ -5489,10 +5555,13 @@ - + - + + + + @@ -5516,10 +5585,13 @@ - + - + + + + @@ -5541,21 +5613,24 @@ - + - + - + - + - + + + + @@ -5570,19 +5645,13 @@ - + - - - - - - - - - - + + + + @@ -5660,10 +5729,13 @@ - + - + + + + @@ -5696,10 +5768,13 @@ - + - + + + + @@ -6980,10 +7055,13 @@ - + - + + + + @@ -7416,15 +7494,6 @@ - - - - - - - - - @@ -8124,15 +8193,6 @@ - - - - - - - - - @@ -8183,10 +8243,13 @@ - + - + + + + @@ -10595,10 +10658,13 @@ - + - + + + + @@ -11813,10 +11879,13 @@ - + - + + + + @@ -11876,10 +11945,13 @@ - + - + + + + @@ -11948,19 +12020,25 @@ - + - + + + + - + - + + + + @@ -12038,10 +12116,13 @@ - + - + + + + @@ -12072,15 +12153,6 @@ - - - - - - - - - @@ -12101,10 +12173,13 @@ - + - + + + + @@ -12122,10 +12197,13 @@ - + - + + + + @@ -12138,6 +12216,15 @@ + + + + + + + + + @@ -12404,10 +12491,13 @@ - + - + + + + @@ -13026,11 +13116,11 @@ - + - + - + @@ -13623,6 +13713,15 @@ + + + + + + + + + @@ -13914,6 +14013,15 @@ + + + + + + + + + @@ -14127,15 +14235,6 @@ - - - - - - - - - @@ -15050,10 +15149,13 @@ - + - + + + + @@ -15528,6 +15630,15 @@ + + + + + + + + + @@ -15564,6 +15675,15 @@ + + + + + + + + + @@ -15804,6 +15924,15 @@ + + + + + + + + + diff --git a/src/loc/lcl/jpn/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/jpn/diagnosticMessages/diagnosticMessages.generated.json.lcl index eb4505d2060..3b0ceb4783d 100644 --- a/src/loc/lcl/jpn/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/jpn/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -963,6 +963,15 @@ + + + + + + + + + @@ -1421,10 +1430,13 @@ - + + + + @@ -1568,10 +1580,13 @@ - + + + + @@ -2462,10 +2477,13 @@ - + - + + + + @@ -3383,10 +3401,13 @@ - + + + + @@ -3879,6 +3900,15 @@ + + + + + + + + + @@ -4605,6 +4635,15 @@ + + + + + + + + + @@ -4670,10 +4709,13 @@ - + - + + + + @@ -4715,10 +4757,13 @@ - + + + + @@ -4844,10 +4889,13 @@ - + + + + @@ -4871,10 +4919,13 @@ - + + + + @@ -4898,10 +4949,13 @@ - + + + + @@ -4925,10 +4979,13 @@ - + - + + + + @@ -5006,10 +5063,13 @@ - + - + + + + @@ -5024,10 +5084,13 @@ - `s from expanding the number of files TypeScript should add to a project.]]> + 's from expanding the number of files TypeScript should add to a project.]]> ' を使用して TypeScript がプロジェクトに追加するファイルの数を増やすことを無効にします。]]> + + `s from expanding the number of files TypeScript should add to a project.]]> + @@ -5435,10 +5498,13 @@ - + + + + @@ -5489,10 +5555,13 @@ - + - + + + + @@ -5516,10 +5585,13 @@ - + + + + @@ -5541,9 +5613,9 @@ - + - + @@ -5552,10 +5624,13 @@ - + + + + @@ -5570,19 +5645,13 @@ - + - - - - - - - - - - + + + + @@ -5660,10 +5729,13 @@ - + - + + + + @@ -5696,10 +5768,13 @@ - + - + + + + @@ -6980,10 +7055,13 @@ - + + + + @@ -7416,15 +7494,6 @@ - - - - - - - - - @@ -8124,15 +8193,6 @@ - - - - - - - - - @@ -8183,10 +8243,13 @@ - + + + + @@ -10595,10 +10658,13 @@ - + - + + + + @@ -11813,10 +11879,13 @@ - + + + + @@ -11876,10 +11945,13 @@ - + - + + + + @@ -11948,19 +12020,25 @@ - + + + + - + + + + @@ -12038,10 +12116,13 @@ - + + + + @@ -12072,15 +12153,6 @@ - - - - - - - - - @@ -12101,10 +12173,13 @@ - + + + + @@ -12122,10 +12197,13 @@ - + + + + @@ -12138,6 +12216,15 @@ + + + + + + + + + @@ -12404,10 +12491,13 @@ - + + + + @@ -13026,11 +13116,11 @@ - + - + - + @@ -13623,6 +13713,15 @@ + + + + + + + + + @@ -13914,6 +14013,15 @@ + + + + + + + + + @@ -14127,15 +14235,6 @@ - - - - - - - - - @@ -15050,10 +15149,13 @@ - + + + + @@ -15528,6 +15630,15 @@ + + + + + + + + + @@ -15564,6 +15675,15 @@ + + + + + + + + + @@ -15804,6 +15924,15 @@ + + + + + + + + + diff --git a/src/loc/lcl/kor/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/kor/diagnosticMessages/diagnosticMessages.generated.json.lcl index b3a08f7917c..aaa0d9488b2 100644 --- a/src/loc/lcl/kor/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/kor/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -963,6 +963,15 @@ + + + + + + + + + @@ -1421,10 +1430,13 @@ - + - + + + + @@ -1568,10 +1580,13 @@ - + - + + + + @@ -2462,10 +2477,13 @@ - + - + + + + @@ -3383,10 +3401,13 @@ - + - + + + + @@ -3879,6 +3900,15 @@ + + + + + + + + + @@ -4605,6 +4635,15 @@ + + + + + + + + + @@ -4670,10 +4709,13 @@ - + - + + + + @@ -4715,10 +4757,13 @@ - + - + + + + @@ -4844,10 +4889,13 @@ - + - + + + + @@ -4871,10 +4919,13 @@ - + - + + + + @@ -4898,10 +4949,13 @@ - + - + + + + @@ -4925,10 +4979,13 @@ - + - + + + + @@ -5006,10 +5063,13 @@ - + - + + + + @@ -5024,10 +5084,13 @@ - `s from expanding the number of files TypeScript should add to a project.]]> + 's from expanding the number of files TypeScript should add to a project.]]> - '에서 확장하지 못하도록 합니다.]]> + '를 허용하지 않습니다.]]> + + `s from expanding the number of files TypeScript should add to a project.]]> + @@ -5435,10 +5498,13 @@ - + - + + + + @@ -5489,10 +5555,13 @@ - + - + + + + @@ -5516,10 +5585,13 @@ - + - + + + + @@ -5541,21 +5613,24 @@ - + - + - + - + - + + + + @@ -5570,19 +5645,13 @@ - + - - - - - - - - - - + + + + @@ -5660,10 +5729,13 @@ - + - + + + + @@ -5696,10 +5768,13 @@ - + - + + + + @@ -6980,10 +7055,13 @@ - + - + + + + @@ -7416,15 +7494,6 @@ - - - - - - - - - @@ -8124,15 +8193,6 @@ - - - - - - - - - @@ -8183,10 +8243,13 @@ - + - + + + + @@ -10595,10 +10658,13 @@ - + - + + + + @@ -11813,10 +11879,13 @@ - + - + + + + @@ -11876,10 +11945,13 @@ - + - + + + + @@ -11948,19 +12020,25 @@ - + - + + + + - + + + + @@ -12038,10 +12116,13 @@ - + - + + + + @@ -12072,15 +12153,6 @@ - - - - - - - - - @@ -12101,10 +12173,13 @@ - + - + + + + @@ -12122,10 +12197,13 @@ - + - + + + + @@ -12138,6 +12216,15 @@ + + + + + + + + + @@ -12404,10 +12491,13 @@ - + - + + + + @@ -13026,11 +13116,11 @@ - + - + - + @@ -13623,6 +13713,15 @@ + + + + + + + + + @@ -13914,6 +14013,15 @@ + + + + + + + + + @@ -14127,15 +14235,6 @@ - - - - - - - - - @@ -15050,10 +15149,13 @@ - + - + + + + @@ -15528,6 +15630,15 @@ + + + + + + + + + @@ -15564,6 +15675,15 @@ + + + + + + + + + @@ -15804,6 +15924,15 @@ + + + + + + + + + diff --git a/src/loc/lcl/plk/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/plk/diagnosticMessages/diagnosticMessages.generated.json.lcl index d54eaf9fe77..148cab39680 100644 --- a/src/loc/lcl/plk/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/plk/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -953,6 +953,15 @@ + + + + + + + + + @@ -1411,10 +1420,13 @@ - + - + + + + @@ -1558,10 +1570,13 @@ - + + + + @@ -2452,10 +2467,13 @@ - + - + + + + @@ -3373,10 +3391,13 @@ - + + + + @@ -3869,6 +3890,15 @@ + + + + + + + + + @@ -4595,6 +4625,15 @@ + + + + + + + + + @@ -4660,10 +4699,13 @@ - + - + + + + @@ -4705,10 +4747,13 @@ - + + + + @@ -4834,10 +4879,13 @@ - + + + + @@ -4861,10 +4909,13 @@ - + + + + @@ -4888,10 +4939,13 @@ - + + + + @@ -4915,10 +4969,13 @@ - + - + + + + @@ -4996,10 +5053,13 @@ - + - + + + + @@ -5014,10 +5074,13 @@ - `s from expanding the number of files TypeScript should add to a project.]]> + 's from expanding the number of files TypeScript should add to a project.]]> ” na zwiększanie liczby plików, które powinny zostać dodane do projektu przez język TypeScript.]]> + + `s from expanding the number of files TypeScript should add to a project.]]> + @@ -5425,10 +5488,13 @@ - + + + + @@ -5479,10 +5545,13 @@ - + - + + + + @@ -5506,10 +5575,13 @@ - + + + + @@ -5531,9 +5603,9 @@ - + - + @@ -5542,10 +5614,13 @@ - + + + + @@ -5560,19 +5635,13 @@ - + - - - - - - - - - - + + + + @@ -5650,10 +5719,13 @@ - + - + + + + @@ -5686,10 +5758,13 @@ - + - + + + + @@ -6970,10 +7045,13 @@ - + - + + + + @@ -7406,15 +7484,6 @@ - - - - - - - - - @@ -8114,15 +8183,6 @@ - - - - - - - - - @@ -8173,10 +8233,13 @@ - + + + + @@ -10582,10 +10645,13 @@ - + - + + + + @@ -11800,10 +11866,13 @@ - + + + + @@ -11863,10 +11932,13 @@ - + - + + + + @@ -11935,19 +12007,25 @@ - + + + + - + + + + @@ -12025,10 +12103,13 @@ - + + + + @@ -12059,15 +12140,6 @@ - - - - - - - - - @@ -12088,10 +12160,13 @@ - + - + + + + @@ -12109,10 +12184,13 @@ - + + + + @@ -12125,6 +12203,15 @@ + + + + + + + + + @@ -12391,10 +12478,13 @@ - + + + + @@ -13013,11 +13103,11 @@ - + - + - + @@ -13610,6 +13700,15 @@ + + + + + + + + + @@ -13901,6 +14000,15 @@ + + + + + + + + + @@ -14114,15 +14222,6 @@ - - - - - - - - - @@ -15037,10 +15136,13 @@ - + - + + + + @@ -15515,6 +15617,15 @@ + + + + + + + + + @@ -15551,6 +15662,15 @@ + + + + + + + + + @@ -15791,6 +15911,15 @@ + + + + + + + + + diff --git a/src/loc/lcl/ptb/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/ptb/diagnosticMessages/diagnosticMessages.generated.json.lcl index 3e75ceff951..d66e5046b5d 100644 --- a/src/loc/lcl/ptb/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/ptb/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -953,6 +953,15 @@ + + + + + + + + + @@ -1414,10 +1423,13 @@ - + - + + + + @@ -1561,10 +1573,13 @@ - + + + + @@ -2455,10 +2470,13 @@ - + - + + + + @@ -3376,10 +3394,13 @@ - + - + + + + @@ -3872,6 +3893,15 @@ + + + + + + + + + @@ -4598,6 +4628,15 @@ + + + + + + + + + @@ -4663,10 +4702,13 @@ - + - + + + + @@ -4708,10 +4750,13 @@ - + + + + @@ -4837,10 +4882,13 @@ - + - + + + + @@ -4864,10 +4912,13 @@ - + - + + + + @@ -4891,10 +4942,13 @@ - + + + + @@ -4918,10 +4972,13 @@ - + - + + + + @@ -4999,10 +5056,13 @@ - + - + + + + @@ -5017,10 +5077,13 @@ - `s from expanding the number of files TypeScript should add to a project.]]> + 's from expanding the number of files TypeScript should add to a project.]]> - de expandir o número de arquivos que TypeScript deve adicionar a um projeto.]]> + de expandir o número de arquivos que TypeScript deve adicionar a um projeto.]]> + + `s from expanding the number of files TypeScript should add to a project.]]> + @@ -5428,10 +5491,13 @@ - + + + + @@ -5482,10 +5548,13 @@ - + - + + + + @@ -5509,10 +5578,13 @@ - + + + + @@ -5534,9 +5606,9 @@ - + - + @@ -5545,10 +5617,13 @@ - + + + + @@ -5563,19 +5638,13 @@ - + - - - - - - - - - - + + + + @@ -5653,10 +5722,13 @@ - + - + + + + @@ -5689,10 +5761,13 @@ - + - + + + + @@ -6973,10 +7048,13 @@ - + - + + + + @@ -7409,15 +7487,6 @@ - - - - - - - - - @@ -8117,15 +8186,6 @@ - - - - - - - - - @@ -8176,10 +8236,13 @@ - + + + + @@ -10585,10 +10648,13 @@ - + - + + + + @@ -11803,10 +11869,13 @@ - + + + + @@ -11866,10 +11935,13 @@ - + - + + + + @@ -11938,19 +12010,25 @@ - + - + + + + - + + + + @@ -12028,10 +12106,13 @@ - + - + + + + @@ -12062,15 +12143,6 @@ - - - - - - - - - @@ -12091,10 +12163,13 @@ - + - + + + + @@ -12112,10 +12187,13 @@ - + - + + + + @@ -12128,6 +12206,15 @@ + + + + + + + + + @@ -12394,10 +12481,13 @@ - + + + + @@ -13016,11 +13106,11 @@ - + - + - + @@ -13613,6 +13703,15 @@ + + + + + + + + + @@ -13904,6 +14003,15 @@ + + + + + + + + + @@ -14117,15 +14225,6 @@ - - - - - - - - - @@ -15040,10 +15139,13 @@ - + + + + @@ -15518,6 +15620,15 @@ + + + + + + + + + @@ -15554,6 +15665,15 @@ + + + + + + + + + @@ -15794,6 +15914,15 @@ + + + + + + + + + diff --git a/src/loc/lcl/rus/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/rus/diagnosticMessages/diagnosticMessages.generated.json.lcl index 736a2074d5c..f9c3e47e744 100644 --- a/src/loc/lcl/rus/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/rus/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -962,6 +962,15 @@ + + + + + + + + + @@ -1420,10 +1429,13 @@ - + - + + + + @@ -1567,10 +1579,13 @@ - + + + + @@ -2461,10 +2476,13 @@ - + - + + + + @@ -3382,10 +3400,13 @@ - + - + + + + @@ -3878,6 +3899,15 @@ + + + + + + + + + @@ -4604,6 +4634,15 @@ + + + + + + + + + @@ -4669,10 +4708,13 @@ - + - + + + + @@ -4714,10 +4756,13 @@ - + + + + @@ -4843,10 +4888,13 @@ - + + + + @@ -4870,10 +4918,13 @@ - + - + + + + @@ -4897,10 +4948,13 @@ - + - + + + + @@ -4924,10 +4978,13 @@ - + - + + + + @@ -5005,10 +5062,13 @@ - + - + + + + @@ -5023,10 +5083,13 @@ - `s from expanding the number of files TypeScript should add to a project.]]> + 's from expanding the number of files TypeScript should add to a project.]]> - " увеличивать количество файлов, которые TypeScript должен добавить в проект.]]> + " увеличивать количество файлов, которые TypeScript должен добавить в проект.]]> + + `s from expanding the number of files TypeScript should add to a project.]]> + @@ -5434,10 +5497,13 @@ - + + + + @@ -5488,10 +5554,13 @@ - + - + + + + @@ -5515,10 +5584,13 @@ - + - + + + + @@ -5540,21 +5612,24 @@ - + - + - + - + - + + + + @@ -5569,19 +5644,13 @@ - + - - - - - - - - - - + + + + @@ -5659,10 +5728,13 @@ - + - + + + + @@ -5695,10 +5767,13 @@ - + - + + + + @@ -6979,10 +7054,13 @@ - + + + + @@ -7415,15 +7493,6 @@ - - - - - - - - - @@ -8123,15 +8192,6 @@ - - - - - - - - - @@ -8182,10 +8242,13 @@ - + + + + @@ -10594,10 +10657,13 @@ - + - + + + + @@ -11812,10 +11878,13 @@ - + + + + @@ -11875,10 +11944,13 @@ - + - + + + + @@ -11947,19 +12019,25 @@ - + + + + - + + + + @@ -12037,10 +12115,13 @@ - + + + + @@ -12071,15 +12152,6 @@ - - - - - - - - - @@ -12100,10 +12172,13 @@ - + + + + @@ -12121,10 +12196,13 @@ - + + + + @@ -12137,6 +12215,15 @@ + + + + + + + + + @@ -12403,10 +12490,13 @@ - + - + + + + @@ -13025,11 +13115,11 @@ - + - + - + @@ -13622,6 +13712,15 @@ + + + + + + + + + @@ -13913,6 +14012,15 @@ + + + + + + + + + @@ -14126,15 +14234,6 @@ - - - - - - - - - @@ -15049,10 +15148,13 @@ - + + + + @@ -15527,6 +15629,15 @@ + + + + + + + + + @@ -15563,6 +15674,15 @@ + + + + + + + + + @@ -15803,6 +15923,15 @@ + + + + + + + + + diff --git a/src/loc/lcl/trk/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/trk/diagnosticMessages/diagnosticMessages.generated.json.lcl index 205b756140b..9f6f2861b6e 100644 --- a/src/loc/lcl/trk/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/trk/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -956,6 +956,15 @@ + + + + + + + + + @@ -1414,10 +1423,13 @@ - + - + + + + @@ -1561,10 +1573,13 @@ - + - + + + + @@ -2455,10 +2470,13 @@ - + - + + + + @@ -3376,10 +3394,13 @@ - + - + + + + @@ -3872,6 +3893,15 @@ + + + + + + + + + @@ -4598,6 +4628,15 @@ + + + + + + + + + @@ -4663,10 +4702,13 @@ - + - + + + + @@ -4708,10 +4750,13 @@ - + - + + + + @@ -4837,10 +4882,13 @@ - + - + + + + @@ -4864,10 +4912,13 @@ - + - + + + + @@ -4891,10 +4942,13 @@ - + - + + + + @@ -4918,10 +4972,13 @@ - + - + + + + @@ -4999,10 +5056,13 @@ - + - + + + + @@ -5017,10 +5077,13 @@ - `s from expanding the number of files TypeScript should add to a project.]]> + 's from expanding the number of files TypeScript should add to a project.]]> - ` öğelerinin, TypeScript’in bir projeye eklemesi gereken dosya sayısını artırmasını engelleyin.]]> + ' ifadelerinin TypeScript'in projeye eklemesi gereken dosya sayısını artırmasına izin verme.]]> + + `s from expanding the number of files TypeScript should add to a project.]]> + @@ -5428,10 +5491,13 @@ - + - + + + + @@ -5482,10 +5548,13 @@ - + - + + + + @@ -5509,10 +5578,13 @@ - + - + + + + @@ -5534,21 +5606,24 @@ - + - + - + - + - + + + + @@ -5563,19 +5638,13 @@ - + - - - - - - - - - - + + + + @@ -5653,10 +5722,13 @@ - + - + + + + @@ -5689,10 +5761,13 @@ - + - + + + + @@ -6973,10 +7048,13 @@ - + - + + + + @@ -7409,15 +7487,6 @@ - - - - - - - - - @@ -8117,15 +8186,6 @@ - - - - - - - - - @@ -8176,10 +8236,13 @@ - + - + + + + @@ -10588,10 +10651,13 @@ - + - + + + + @@ -11806,10 +11872,13 @@ - + - + + + + @@ -11869,10 +11938,13 @@ - + - + + + + @@ -11941,19 +12013,25 @@ - + - + + + + - + - + + + + @@ -12031,10 +12109,13 @@ - + - + + + + @@ -12065,15 +12146,6 @@ - - - - - - - - - @@ -12094,10 +12166,13 @@ - + - + + + + @@ -12115,10 +12190,13 @@ - + - + + + + @@ -12131,6 +12209,15 @@ + + + + + + + + + @@ -12397,10 +12484,13 @@ - + - + + + + @@ -13019,11 +13109,11 @@ - + - + - + @@ -13616,6 +13706,15 @@ + + + + + + + + + @@ -13907,6 +14006,15 @@ + + + + + + + + + @@ -14120,15 +14228,6 @@ - - - - - - - - - @@ -15043,10 +15142,13 @@ - + - + + + + @@ -15521,6 +15623,15 @@ + + + + + + + + + @@ -15557,6 +15668,15 @@ + + + + + + + + + @@ -15797,6 +15917,15 @@ + + + + + + + + + diff --git a/src/server/editorServices.ts b/src/server/editorServices.ts index 343303ef33b..594fc7c2e07 100644 --- a/src/server/editorServices.ts +++ b/src/server/editorServices.ts @@ -2064,6 +2064,7 @@ namespace ts.server { /* @internal */ createConfiguredProject(configFileName: NormalizedPath) { + tracing?.instant(tracing.Phase.Session, "createConfiguredProject", { configFilePath: configFileName }); this.logger.info(`Creating configuration project ${configFileName}`); const canonicalConfigFilePath = asNormalizedPath(this.toCanonicalFileName(configFileName)); let configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath); @@ -2121,6 +2122,7 @@ namespace ts.server { */ /* @internal */ private loadConfiguredProject(project: ConfiguredProject, reason: string) { + tracing?.push(tracing.Phase.Session, "loadConfiguredProject", { configFilePath: project.canonicalConfigFilePath }); this.sendProjectLoadingStartEvent(project, reason); // Read updated contents from disk @@ -2162,6 +2164,7 @@ namespace ts.server { project.enablePluginsWithOptions(compilerOptions, this.currentPluginConfigOverrides); const filesToAdd = parsedCommandLine.fileNames.concat(project.getExternalFiles()); this.updateRootAndOptionsOfNonInferredProject(project, filesToAdd, fileNamePropertyReader, compilerOptions, parsedCommandLine.typeAcquisition!, parsedCommandLine.compileOnSave, parsedCommandLine.watchOptions); + tracing?.pop(); } /*@internal*/ diff --git a/src/server/project.ts b/src/server/project.ts index 91bc1e639a3..cabeb6d1e62 100644 --- a/src/server/project.ts +++ b/src/server/project.ts @@ -1045,6 +1045,7 @@ namespace ts.server { * @returns: true if set of files in the project stays the same and false - otherwise. */ updateGraph(): boolean { + tracing?.push(tracing.Phase.Session, "updateGraph", { name: this.projectName, kind: ProjectKind[this.projectKind] }); perfLogger.logStartUpdateGraph(); this.resolutionCache.startRecordingFilesWithChangedResolutions(); @@ -1092,6 +1093,7 @@ namespace ts.server { this.getPackageJsonAutoImportProvider(); } perfLogger.logStopUpdateGraph(); + tracing?.pop(); return !hasNewProgram; } @@ -1128,7 +1130,9 @@ namespace ts.server { this.resolutionCache.startCachingPerDirectoryResolution(); this.program = this.languageService.getProgram(); // TODO: GH#18217 this.dirty = false; + tracing?.push(tracing.Phase.Session, "finishCachingPerDirectoryResolution"); this.resolutionCache.finishCachingPerDirectoryResolution(); + tracing?.pop(); Debug.assert(oldProgram === undefined || this.program !== undefined); @@ -1747,13 +1751,16 @@ namespace ts.server { const dependencySelection = this.includePackageJsonAutoImports(); if (dependencySelection) { + tracing?.push(tracing.Phase.Session, "getPackageJsonAutoImportProvider"); const start = timestamp(); this.autoImportProviderHost = AutoImportProviderProject.create(dependencySelection, this, this.getModuleResolutionHostForAutoImportProvider(), this.documentRegistry); if (this.autoImportProviderHost) { updateProjectIfDirty(this.autoImportProviderHost); this.sendPerformanceEvent("CreatePackageJsonAutoImportProvider", timestamp() - start); + tracing?.pop(); return this.autoImportProviderHost.getCurrentProgram(); } + tracing?.pop(); } } @@ -1776,9 +1783,13 @@ namespace ts.server { } function getUnresolvedImports(program: Program, cachedUnresolvedImportsPerFile: ESMap): SortedReadonlyArray { + const sourceFiles = program.getSourceFiles(); + tracing?.push(tracing.Phase.Session, "getUnresolvedImports", { count: sourceFiles.length }); const ambientModules = program.getTypeChecker().getAmbientModules().map(mod => stripQuotes(mod.getName())); - return sortAndDeduplicate(flatMap(program.getSourceFiles(), sourceFile => + const result = sortAndDeduplicate(flatMap(sourceFiles, sourceFile => extractUnresolvedImportsFromSourceFile(sourceFile, ambientModules, cachedUnresolvedImportsPerFile))); + tracing?.pop(); + return result; } function extractUnresolvedImportsFromSourceFile(file: SourceFile, ambientModules: readonly string[], cachedUnresolvedImportsPerFile: ESMap): readonly string[] { return getOrUpdate(cachedUnresolvedImportsPerFile, file.path, () => { @@ -1963,19 +1974,26 @@ namespace ts.server { } } - // 2. Try to load from the @types package. - const typesPackageJson = resolvePackageNameToPackageJson( - `@types/${name}`, - hostProject.currentDirectory, - compilerOptions, - moduleResolutionHost, - program.getModuleResolutionCache()); - if (typesPackageJson) { - const entrypoints = getRootNamesFromPackageJson(typesPackageJson, program, symlinkCache); - rootNames = concatenate(rootNames, entrypoints); - dependenciesAdded += entrypoints?.length ? 1 : 0; - continue; - } + // 2. Try to load from the @types package in the tree and in the global + // typings cache location, if enabled. + const done = forEach([hostProject.currentDirectory, hostProject.getGlobalTypingsCacheLocation()], directory => { + if (directory) { + const typesPackageJson = resolvePackageNameToPackageJson( + `@types/${name}`, + directory, + compilerOptions, + moduleResolutionHost, + program.getModuleResolutionCache()); + if (typesPackageJson) { + const entrypoints = getRootNamesFromPackageJson(typesPackageJson, program, symlinkCache); + rootNames = concatenate(rootNames, entrypoints); + dependenciesAdded += entrypoints?.length ? 1 : 0; + return true; + } + } + }); + + if (done) continue; // 3. If the @types package did not exist and the user has settings that // allow processing JS from node_modules, go back to the implementation diff --git a/src/server/session.ts b/src/server/session.ts index d66803433ff..e2257767105 100644 --- a/src/server/session.ts +++ b/src/server/session.ts @@ -905,7 +905,6 @@ namespace ts.server { } public event(body: T, eventName: string): void { - tracing?.instant(tracing.Phase.Session, "event", { eventName }); this.send(toEvent(eventName, body)); } @@ -957,18 +956,24 @@ namespace ts.server { } private semanticCheck(file: NormalizedPath, project: Project) { + tracing?.push(tracing.Phase.Session, "semanticCheck", { file, configFilePath: (project as ConfiguredProject).canonicalConfigFilePath }); // undefined is fine if the cast fails const diags = isDeclarationFileInJSOnlyNonConfiguredProject(project, file) ? emptyArray : project.getLanguageService().getSemanticDiagnostics(file).filter(d => !!d.file); this.sendDiagnosticsEvent(file, project, diags, "semanticDiag"); + tracing?.pop(); } private syntacticCheck(file: NormalizedPath, project: Project) { + tracing?.push(tracing.Phase.Session, "syntacticCheck", { file, configFilePath: (project as ConfiguredProject).canonicalConfigFilePath }); // undefined is fine if the cast fails this.sendDiagnosticsEvent(file, project, project.getLanguageService().getSyntacticDiagnostics(file), "syntaxDiag"); + tracing?.pop(); } private suggestionCheck(file: NormalizedPath, project: Project) { + tracing?.push(tracing.Phase.Session, "suggestionCheck", { file, configFilePath: (project as ConfiguredProject).canonicalConfigFilePath }); // undefined is fine if the cast fails this.sendDiagnosticsEvent(file, project, project.getLanguageService().getSuggestionDiagnostics(file), "suggestionDiag"); + tracing?.pop(); } private sendDiagnosticsEvent(file: NormalizedPath, project: Project, diagnostics: readonly Diagnostic[], kind: protocol.DiagnosticEventKind): void { diff --git a/src/services/codefixes/addMissingAsync.ts b/src/services/codefixes/addMissingAsync.ts index bb076588a45..de12496f865 100644 --- a/src/services/codefixes/addMissingAsync.ts +++ b/src/services/codefixes/addMissingAsync.ts @@ -13,7 +13,7 @@ namespace ts.codefix { errorCodes, getCodeActions: function getCodeActionsToAddMissingAsync(context) { const { sourceFile, errorCode, cancellationToken, program, span } = context; - const diagnostic = find(program.getDiagnosticsProducingTypeChecker().getDiagnostics(sourceFile, cancellationToken), getIsMatchingAsyncError(span, errorCode)); + const diagnostic = find(program.getTypeChecker().getDiagnostics(sourceFile, cancellationToken), getIsMatchingAsyncError(span, errorCode)); const directSpan = diagnostic && diagnostic.relatedInformation && find(diagnostic.relatedInformation, r => r.code === Diagnostics.Did_you_mean_to_mark_this_function_as_async.code) as TextSpan | undefined; const decl = getFixableErrorSpanDeclaration(sourceFile, directSpan); diff --git a/src/services/codefixes/addMissingAwait.ts b/src/services/codefixes/addMissingAwait.ts index 3853a52b724..1a9110227e5 100644 --- a/src/services/codefixes/addMissingAwait.ts +++ b/src/services/codefixes/addMissingAwait.ts @@ -93,7 +93,7 @@ namespace ts.codefix { } function isMissingAwaitError(sourceFile: SourceFile, errorCode: number, span: TextSpan, cancellationToken: CancellationToken, program: Program) { - const checker = program.getDiagnosticsProducingTypeChecker(); + const checker = program.getTypeChecker(); const diagnostics = checker.getDiagnostics(sourceFile, cancellationToken); return some(diagnostics, ({ start, length, relatedInformation, code }) => isNumber(start) && isNumber(length) && textSpansEqual({ start, length }, span) && diff --git a/src/services/codefixes/convertFunctionToEs6Class.ts b/src/services/codefixes/convertFunctionToEs6Class.ts index 8a20f68840d..352fbbb5bc1 100644 --- a/src/services/codefixes/convertFunctionToEs6Class.ts +++ b/src/services/codefixes/convertFunctionToEs6Class.ts @@ -43,21 +43,6 @@ namespace ts.codefix { function createClassElementsFromSymbol(symbol: Symbol) { const memberElements: ClassElement[] = []; - // all instance members are stored in the "member" array of symbol - if (symbol.members) { - symbol.members.forEach((member, key) => { - if (key === "constructor" && member.valueDeclaration) { - // fn.prototype.constructor = fn - changes.delete(sourceFile, member.valueDeclaration.parent); - return; - } - const memberElement = createClassElement(member, /*modifiers*/ undefined); - if (memberElement) { - memberElements.push(...memberElement); - } - }); - } - // all static members are stored in the "exports" array of symbol if (symbol.exports) { symbol.exports.forEach(member => { @@ -71,21 +56,34 @@ namespace ts.codefix { isObjectLiteralExpression(firstDeclaration.parent.right) ) { const prototypes = firstDeclaration.parent.right; - const memberElement = createClassElement(prototypes.symbol, /** modifiers */ undefined); - if (memberElement) { - memberElements.push(...memberElement); - } + createClassElement(prototypes.symbol, /** modifiers */ undefined, memberElements); } } else { - const memberElement = createClassElement(member, [factory.createToken(SyntaxKind.StaticKeyword)]); - if (memberElement) { - memberElements.push(...memberElement); - } + createClassElement(member, [factory.createToken(SyntaxKind.StaticKeyword)], memberElements); } }); } + // all instance members are stored in the "member" array of symbol (done last so instance members pulled from prototype assignments have priority) + if (symbol.members) { + symbol.members.forEach((member, key) => { + if (key === "constructor" && member.valueDeclaration) { + const prototypeAssignment = symbol.exports?.get("prototype" as __String)?.declarations?.[0]?.parent; + if (prototypeAssignment && isBinaryExpression(prototypeAssignment) && isObjectLiteralExpression(prototypeAssignment.right) && some(prototypeAssignment.right.properties, isConstructorAssignment)) { + // fn.prototype = { constructor: fn } + // Already deleted in `createClassElement` in first pass + } + else { + // fn.prototype.constructor = fn + changes.delete(sourceFile, member.valueDeclaration.parent); + } + return; + } + createClassElement(member, /*modifiers*/ undefined, memberElements); + }); + } + return memberElements; function shouldConvertDeclaration(_target: AccessExpression | ObjectLiteralExpression, source: Expression) { @@ -109,19 +107,28 @@ namespace ts.codefix { } } - function createClassElement(symbol: Symbol, modifiers: Modifier[] | undefined): readonly ClassElement[] { + function createClassElement(symbol: Symbol, modifiers: Modifier[] | undefined, members: ClassElement[]): void { // Right now the only thing we can convert are function expressions, which are marked as methods // or { x: y } type prototype assignments, which are marked as ObjectLiteral - const members: ClassElement[] = []; if (!(symbol.flags & SymbolFlags.Method) && !(symbol.flags & SymbolFlags.ObjectLiteral)) { - return members; + return; } const memberDeclaration = symbol.valueDeclaration as AccessExpression | ObjectLiteralExpression; const assignmentBinaryExpression = memberDeclaration.parent as BinaryExpression; const assignmentExpr = assignmentBinaryExpression.right; if (!shouldConvertDeclaration(memberDeclaration, assignmentExpr)) { - return members; + return; + } + + if (some(members, m => { + const name = getNameOfDeclaration(m); + if (name && isIdentifier(name) && idText(name) === symbolName(symbol)) { + return true; // class member already made for this name + } + return false; + })) { + return; } // delete the entire statement if this expression is the sole expression to take care of the semicolon at the end @@ -132,7 +139,7 @@ namespace ts.codefix { if (!assignmentExpr) { members.push(factory.createPropertyDeclaration([], modifiers, symbol.name, /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined)); - return members; + return; } // f.x = expr @@ -140,52 +147,54 @@ namespace ts.codefix { const quotePreference = getQuotePreference(sourceFile, preferences); const name = tryGetPropertyName(memberDeclaration, compilerOptions, quotePreference); if (name) { - return createFunctionLikeExpressionMember(members, assignmentExpr, name); + createFunctionLikeExpressionMember(members, assignmentExpr, name); } - return members; + return; } // f.prototype = { ... } else if (isObjectLiteralExpression(assignmentExpr)) { - return flatMap( + forEach( assignmentExpr.properties, property => { if (isMethodDeclaration(property) || isGetOrSetAccessorDeclaration(property)) { // MethodDeclaration and AccessorDeclaration can appear in a class directly - return members.concat(property); + members.push(property); } if (isPropertyAssignment(property) && isFunctionExpression(property.initializer)) { - return createFunctionLikeExpressionMember(members, property.initializer, property.name); + createFunctionLikeExpressionMember(members, property.initializer, property.name); } // Drop constructor assignments - if (isConstructorAssignment(property)) return members; - return []; + if (isConstructorAssignment(property)) return; + return; } ); + return; } else { // Don't try to declare members in JavaScript files - if (isSourceFileJS(sourceFile)) return members; - if (!isPropertyAccessExpression(memberDeclaration)) return members; + if (isSourceFileJS(sourceFile)) return; + if (!isPropertyAccessExpression(memberDeclaration)) return; const prop = factory.createPropertyDeclaration(/*decorators*/ undefined, modifiers, memberDeclaration.name, /*questionToken*/ undefined, /*type*/ undefined, assignmentExpr); copyLeadingComments(assignmentBinaryExpression.parent, prop, sourceFile); members.push(prop); - return members; + return; } - function createFunctionLikeExpressionMember(members: readonly ClassElement[], expression: FunctionExpression | ArrowFunction, name: PropertyName) { + function createFunctionLikeExpressionMember(members: ClassElement[], expression: FunctionExpression | ArrowFunction, name: PropertyName) { if (isFunctionExpression(expression)) return createFunctionExpressionMember(members, expression, name); else return createArrowFunctionExpressionMember(members, expression, name); } - function createFunctionExpressionMember(members: readonly ClassElement[], functionExpression: FunctionExpression, name: PropertyName) { + function createFunctionExpressionMember(members: ClassElement[], functionExpression: FunctionExpression, name: PropertyName) { const fullModifiers = concatenate(modifiers, getModifierKindFromSource(functionExpression, SyntaxKind.AsyncKeyword)); const method = factory.createMethodDeclaration(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, name, /*questionToken*/ undefined, /*typeParameters*/ undefined, functionExpression.parameters, /*type*/ undefined, functionExpression.body); copyLeadingComments(assignmentBinaryExpression, method, sourceFile); - return members.concat(method); + members.push(method); + return; } - function createArrowFunctionExpressionMember(members: readonly ClassElement[], arrowFunction: ArrowFunction, name: PropertyName) { + function createArrowFunctionExpressionMember(members: ClassElement[], arrowFunction: ArrowFunction, name: PropertyName) { const arrowFunctionBody = arrowFunction.body; let bodyBlock: Block; @@ -201,7 +210,7 @@ namespace ts.codefix { const method = factory.createMethodDeclaration(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, name, /*questionToken*/ undefined, /*typeParameters*/ undefined, arrowFunction.parameters, /*type*/ undefined, bodyBlock); copyLeadingComments(assignmentBinaryExpression, method, sourceFile); - return members.concat(method); + members.push(method); } } } diff --git a/src/services/codefixes/convertLiteralTypeToMappedType.ts b/src/services/codefixes/convertLiteralTypeToMappedType.ts index b6b2fd83a6f..9c5d03e09d8 100644 --- a/src/services/codefixes/convertLiteralTypeToMappedType.ts +++ b/src/services/codefixes/convertLiteralTypeToMappedType.ts @@ -49,7 +49,7 @@ namespace ts.codefix { function doChange(changes: textChanges.ChangeTracker, sourceFile: SourceFile, { container, typeNode, constraint, name }: Info): void { changes.replaceNode(sourceFile, container, factory.createMappedTypeNode( /*readonlyToken*/ undefined, - factory.createTypeParameterDeclaration(name, factory.createTypeReferenceNode(constraint)), + factory.createTypeParameterDeclaration(/*modifiers*/ undefined, name, factory.createTypeReferenceNode(constraint)), /*nameType*/ undefined, /*questionToken*/ undefined, typeNode, diff --git a/src/services/codefixes/convertToMappedObjectType.ts b/src/services/codefixes/convertToMappedObjectType.ts index 7f9f6af4e80..13429f17ec9 100644 --- a/src/services/codefixes/convertToMappedObjectType.ts +++ b/src/services/codefixes/convertToMappedObjectType.ts @@ -42,7 +42,7 @@ namespace ts.codefix { const members = isInterfaceDeclaration(container) ? container.members : (container.type as TypeLiteralNode).members; const otherMembers = members.filter(member => !isIndexSignatureDeclaration(member)); const parameter = first(indexSignature.parameters); - const mappedTypeParameter = factory.createTypeParameterDeclaration(cast(parameter.name, isIdentifier), parameter.type); + const mappedTypeParameter = factory.createTypeParameterDeclaration(/*modifiers*/ undefined, cast(parameter.name, isIdentifier), parameter.type); const mappedIntersectionType = factory.createMappedTypeNode( hasEffectiveReadonlyModifier(indexSignature) ? factory.createModifier(SyntaxKind.ReadonlyKeyword) : undefined, mappedTypeParameter, diff --git a/src/services/codefixes/fixAddMissingMember.ts b/src/services/codefixes/fixAddMissingMember.ts index 0eb72741b43..163cd7234a2 100644 --- a/src/services/codefixes/fixAddMissingMember.ts +++ b/src/services/codefixes/fixAddMissingMember.ts @@ -171,7 +171,7 @@ namespace ts.codefix { const properties = arrayFrom(checker.getUnmatchedProperties(checker.getTypeAtLocation(parent), checker.getTypeAtLocation(param), /* requireOptionalProperties */ false, /* matchDiscriminantProperties */ false)); if (!length(properties)) return undefined; - return { kind: InfoKind.ObjectLiteral, token: param.name, properties, indentation: 0, parentDeclaration: parent }; + return { kind: InfoKind.ObjectLiteral, token: param.name, properties, parentDeclaration: parent }; } if (!isMemberName(token)) return undefined; @@ -179,7 +179,8 @@ namespace ts.codefix { if (isIdentifier(token) && hasInitializer(parent) && parent.initializer && isObjectLiteralExpression(parent.initializer)) { const properties = arrayFrom(checker.getUnmatchedProperties(checker.getTypeAtLocation(parent.initializer), checker.getTypeAtLocation(token), /* requireOptionalProperties */ false, /* matchDiscriminantProperties */ false)); if (!length(properties)) return undefined; - return { kind: InfoKind.ObjectLiteral, token, properties, indentation: undefined, parentDeclaration: parent.initializer }; + + return { kind: InfoKind.ObjectLiteral, token, properties, parentDeclaration: parent.initializer }; } if (isIdentifier(token) && isJsxOpeningLikeElement(token.parent)) { @@ -235,6 +236,7 @@ namespace ts.codefix { if (enumDeclaration && !isPrivateIdentifier(token) && !isSourceFileFromLibrary(program, enumDeclaration.getSourceFile())) { return { kind: InfoKind.Enum, token, parentDeclaration: enumDeclaration }; } + return undefined; } diff --git a/src/services/codefixes/fixStrictClassInitialization.ts b/src/services/codefixes/fixStrictClassInitialization.ts index f9fcad0f2d7..67f5e41f7d4 100644 --- a/src/services/codefixes/fixStrictClassInitialization.ts +++ b/src/services/codefixes/fixStrictClassInitialization.ts @@ -67,6 +67,7 @@ namespace ts.codefix { } function addDefiniteAssignmentAssertion(changeTracker: textChanges.ChangeTracker, propertyDeclarationSourceFile: SourceFile, propertyDeclaration: PropertyDeclaration): void { + suppressLeadingAndTrailingTrivia(propertyDeclaration); const property = factory.updatePropertyDeclaration( propertyDeclaration, propertyDeclaration.decorators, @@ -108,6 +109,7 @@ namespace ts.codefix { } function addInitializer(changeTracker: textChanges.ChangeTracker, propertyDeclarationSourceFile: SourceFile, propertyDeclaration: PropertyDeclaration, initializer: Expression): void { + suppressLeadingAndTrailingTrivia(propertyDeclaration); const property = factory.updatePropertyDeclaration( propertyDeclaration, propertyDeclaration.decorators, diff --git a/src/services/codefixes/fixUnreferenceableDecoratorMetadata.ts b/src/services/codefixes/fixUnreferenceableDecoratorMetadata.ts new file mode 100644 index 00000000000..30fefde64ef --- /dev/null +++ b/src/services/codefixes/fixUnreferenceableDecoratorMetadata.ts @@ -0,0 +1,70 @@ +/* @internal */ +namespace ts.codefix { + const fixId = "fixUnreferenceableDecoratorMetadata"; + const errorCodes = [Diagnostics.A_type_referenced_in_a_decorated_signature_must_be_imported_with_import_type_or_a_namespace_import_when_isolatedModules_and_emitDecoratorMetadata_are_enabled.code]; + registerCodeFix({ + errorCodes, + getCodeActions: context => { + const importDeclaration = getImportDeclaration(context.sourceFile, context.program, context.span.start); + if (!importDeclaration) return; + + const namespaceChanges = textChanges.ChangeTracker.with(context, t => importDeclaration.kind === SyntaxKind.ImportSpecifier && doNamespaceImportChange(t, context.sourceFile, importDeclaration, context.program)); + const typeOnlyChanges = textChanges.ChangeTracker.with(context, t => doTypeOnlyImportChange(t, context.sourceFile, importDeclaration, context.program)); + let actions: CodeFixAction[] | undefined; + if (namespaceChanges.length) { + actions = append(actions, createCodeFixActionWithoutFixAll(fixId, namespaceChanges, Diagnostics.Convert_named_imports_to_namespace_import)); + } + if (typeOnlyChanges.length) { + actions = append(actions, createCodeFixActionWithoutFixAll(fixId, typeOnlyChanges, Diagnostics.Convert_to_type_only_import)); + } + return actions; + }, + fixIds: [fixId], + }); + + function getImportDeclaration(sourceFile: SourceFile, program: Program, start: number): ImportClause | ImportSpecifier | ImportEqualsDeclaration | undefined { + const identifier = tryCast(getTokenAtPosition(sourceFile, start), isIdentifier); + if (!identifier || identifier.parent.kind !== SyntaxKind.TypeReference) return; + + const checker = program.getTypeChecker(); + const symbol = checker.getSymbolAtLocation(identifier); + return find(symbol?.declarations || emptyArray, or(isImportClause, isImportSpecifier, isImportEqualsDeclaration) as (n: Node) => n is ImportClause | ImportSpecifier | ImportEqualsDeclaration); + } + + // Converts the import declaration of the offending import to a type-only import, + // only if it can be done without affecting other imported names. If the conversion + // cannot be done cleanly, we could offer to *extract* the offending import to a + // new type-only import declaration, but honestly I doubt anyone will ever use this + // codefix at all, so it's probably not worth the lines of code. + function doTypeOnlyImportChange(changes: textChanges.ChangeTracker, sourceFile: SourceFile, importDeclaration: ImportClause | ImportSpecifier | ImportEqualsDeclaration, program: Program) { + if (importDeclaration.kind === SyntaxKind.ImportEqualsDeclaration) { + changes.insertModifierBefore(sourceFile, SyntaxKind.TypeKeyword, importDeclaration.name); + return; + } + + const importClause = importDeclaration.kind === SyntaxKind.ImportClause ? importDeclaration : importDeclaration.parent.parent; + if (importClause.name && importClause.namedBindings) { + // Cannot convert an import with a default import and named bindings to type-only + // (it's a grammar error). + return; + } + + const checker = program.getTypeChecker(); + const importsValue = !!forEachImportClauseDeclaration(importClause, decl => { + if (skipAlias(decl.symbol, checker).flags & SymbolFlags.Value) return true; + }); + + if (importsValue) { + // Assume that if someone wrote a non-type-only import that includes some values, + // they intend to use those values in value positions, even if they haven't yet. + // Don't convert it to type-only. + return; + } + + changes.insertModifierBefore(sourceFile, SyntaxKind.TypeKeyword, importClause); + } + + function doNamespaceImportChange(changes: textChanges.ChangeTracker, sourceFile: SourceFile, importDeclaration: ImportSpecifier, program: Program) { + refactor.doChangeNamedToNamespaceOrDefault(sourceFile, program, changes, importDeclaration.parent); + } +} diff --git a/src/services/codefixes/helpers.ts b/src/services/codefixes/helpers.ts index baeb1e9a1a5..c34148453b4 100644 --- a/src/services/codefixes/helpers.ts +++ b/src/services/codefixes/helpers.ts @@ -222,6 +222,7 @@ namespace ts.codefix { } return factory.updateTypeParameterDeclaration( typeParameterDecl, + typeParameterDecl.modifiers, typeParameterDecl.name, constraint, defaultType @@ -306,7 +307,7 @@ namespace ts.codefix { const typeParameters = isJs || typeArguments === undefined ? undefined : map(typeArguments, (_, i) => - factory.createTypeParameterDeclaration(CharacterCodes.T + typeArguments.length - 1 <= CharacterCodes.Z ? String.fromCharCode(CharacterCodes.T + i) : `T${i}`)); + factory.createTypeParameterDeclaration(/*modifiers*/ undefined, CharacterCodes.T + typeArguments.length - 1 <= CharacterCodes.Z ? String.fromCharCode(CharacterCodes.T + i) : `T${i}`)); const parameters = createDummyParameters(args.length, names, types, /*minArgumentCount*/ undefined, isJs); const type = isJs || contextualType === undefined ? undefined diff --git a/src/services/completions.ts b/src/services/completions.ts index 6faa7fe88e9..4af2079616e 100644 --- a/src/services/completions.ts +++ b/src/services/completions.ts @@ -17,14 +17,15 @@ namespace ts.Completions { SuggestedClassMembers = "14", GlobalsOrKeywords = "15", AutoImportSuggestions = "16", - JavascriptIdentifiers = "17", - DeprecatedLocalDeclarationPriority = "18", - DeprecatedLocationPriority = "19", - DeprecatedOptionalMember = "20", - DeprecatedMemberDeclaredBySpreadAssignment = "21", - DeprecatedSuggestedClassMembers = "22", - DeprecatedGlobalsOrKeywords = "23", - DeprecatedAutoImportSuggestions = "24" + ClassMemberSnippets = "17", + JavascriptIdentifiers = "18", + DeprecatedLocalDeclarationPriority = "19", + DeprecatedLocationPriority = "20", + DeprecatedOptionalMember = "21", + DeprecatedMemberDeclaredBySpreadAssignment = "22", + DeprecatedSuggestedClassMembers = "23", + DeprecatedGlobalsOrKeywords = "24", + DeprecatedAutoImportSuggestions = "25" } const enum SortTextId { @@ -37,8 +38,8 @@ namespace ts.Completions { AutoImportSuggestions = 16, // Don't use these directly. - _JavaScriptIdentifiers = 17, - _DeprecatedStart = 18, + _JavaScriptIdentifiers = 18, + _DeprecatedStart = 19, _First = LocalDeclarationPriority, DeprecatedOffset = _DeprecatedStart - _First, @@ -769,6 +770,7 @@ namespace ts.Completions { isClassLikeMemberCompletion(symbol, location)) { let importAdder; ({ insertText, isSnippet, importAdder, replacementSpan } = getEntryForMemberCompletion(host, program, options, preferences, name, symbol, location, contextToken, formatContext)); + sortText = SortText.ClassMemberSnippets; // sortText has to be lower priority than the sortText for keywords. See #47852. if (importAdder?.hasFixes()) { hasAction = true; source = CompletionSource.ClassMemberSnippet; @@ -3911,9 +3913,14 @@ namespace ts.Completions { if (type) { return type; } - if (isBinaryExpression(node.parent) && node.parent.operatorToken.kind === SyntaxKind.EqualsToken && node === node.parent.left) { + const parent = walkUpParenthesizedExpressions(node.parent); + if (isBinaryExpression(parent) && parent.operatorToken.kind === SyntaxKind.EqualsToken && node === parent.left) { // Object literal is assignment pattern: ({ | } = x) - return typeChecker.getTypeAtLocation(node.parent); + return typeChecker.getTypeAtLocation(parent); + } + if (isExpression(parent)) { + // f(() => (({ | }))); + return typeChecker.getContextualType(parent); } return undefined; } diff --git a/src/services/documentRegistry.ts b/src/services/documentRegistry.ts index 7446f895db2..88d7daf468b 100644 --- a/src/services/documentRegistry.ts +++ b/src/services/documentRegistry.ts @@ -357,7 +357,23 @@ namespace ts { }; } + function compilerOptionValueToString(value: unknown): string { + if (value === null || typeof value !== "object") { // eslint-disable-line no-null/no-null + return "" + value; + } + if (isArray(value)) { + return `[${map(value, e => compilerOptionValueToString(e))?.join(",")}]`; + } + let str = "{"; + for (const key in value) { + if (ts.hasOwnProperty.call(value, key)) { // eslint-disable-line @typescript-eslint/no-unnecessary-qualifier + str += `${key}: ${compilerOptionValueToString((value as any)[key])}`; + } + } + return str + "}"; + } + function getKeyForCompilationSettings(settings: CompilerOptions): DocumentRegistryBucketKey { - return sourceFileAffectingCompilerOptions.map(option => getCompilerOptionValue(settings, option)).join("|") as DocumentRegistryBucketKey; + return sourceFileAffectingCompilerOptions.map(option => compilerOptionValueToString(getCompilerOptionValue(settings, option))).join("|") + (settings.pathsBasePath ? `|${settings.pathsBasePath}` : undefined) as DocumentRegistryBucketKey; } } diff --git a/src/services/exportInfoMap.ts b/src/services/exportInfoMap.ts index 51a0dd2ce23..4004815a4a6 100644 --- a/src/services/exportInfoMap.ts +++ b/src/services/exportInfoMap.ts @@ -59,6 +59,7 @@ namespace ts { export interface CacheableExportInfoMapHost { getCurrentProgram(): Program | undefined; getPackageJsonAutoImportProvider(): Program | undefined; + getGlobalTypingsCacheLocation(): string | undefined; } export function createCacheableExportInfoMap(host: CacheableExportInfoMapHost): ExportInfoMap { @@ -99,7 +100,7 @@ namespace ts { packageName = unmangleScopedPackageName(getPackageNameFromTypesPackageName(moduleFile.fileName.substring(topLevelPackageNameIndex + 1, packageRootIndex))); if (startsWith(importingFile, moduleFile.path.substring(0, topLevelNodeModulesIndex))) { const prevDeepestNodeModulesPath = packages.get(packageName); - const nodeModulesPath = moduleFile.fileName.substring(0, topLevelPackageNameIndex); + const nodeModulesPath = moduleFile.fileName.substring(0, topLevelPackageNameIndex + 1); if (prevDeepestNodeModulesPath) { const prevDeepestNodeModulesIndex = prevDeepestNodeModulesPath.indexOf(nodeModulesPathPart); if (topLevelNodeModulesIndex > prevDeepestNodeModulesIndex) { @@ -272,6 +273,8 @@ namespace ts { function isNotShadowedByDeeperNodeModulesPackage(info: SymbolExportInfo, packageName: string | undefined) { if (!packageName || !info.moduleFileName) return true; + const typingsCacheLocation = host.getGlobalTypingsCacheLocation(); + if (typingsCacheLocation && startsWith(info.moduleFileName, typingsCacheLocation)) return true; const packageDeepestNodeModulesPath = packages.get(packageName); return !packageDeepestNodeModulesPath || startsWith(info.moduleFileName, packageDeepestNodeModulesPath); } @@ -367,6 +370,7 @@ namespace ts { const cache = host.getCachedExportInfoMap?.() || createCacheableExportInfoMap({ getCurrentProgram: () => program, getPackageJsonAutoImportProvider: () => host.getPackageJsonAutoImportProvider?.(), + getGlobalTypingsCacheLocation: () => host.getGlobalTypingsCacheLocation?.(), }); if (cache.isUsableByFile(importingFile.path)) { diff --git a/src/services/findAllReferences.ts b/src/services/findAllReferences.ts index 952266d5ebc..636ea64ecea 100644 --- a/src/services/findAllReferences.ts +++ b/src/services/findAllReferences.ts @@ -1673,6 +1673,12 @@ namespace ts.FindAllReferences { function addReference(referenceLocation: Node, relatedSymbol: Symbol | RelatedSymbol, state: State): void { const { kind, symbol } = "kind" in relatedSymbol ? relatedSymbol : { kind: undefined, symbol: relatedSymbol }; // eslint-disable-line no-in-operator + + // if rename symbol from default export anonymous function, for example `export default function() {}`, we do not need to add reference + if (state.options.use === FindReferencesUse.Rename && referenceLocation.kind === SyntaxKind.DefaultKeyword) { + return; + } + const addRef = state.referenceAdder(symbol); if (state.options.implementations) { addImplementationReferences(referenceLocation, addRef, state); diff --git a/src/services/formatting/formatting.ts b/src/services/formatting/formatting.ts index 3b68b44063e..5a9948cd35f 100644 --- a/src/services/formatting/formatting.ts +++ b/src/services/formatting/formatting.ts @@ -439,20 +439,21 @@ namespace ts.formatting { } if (previousRange! && formattingScanner.getStartPos() >= originalRange.end) { - const token = + const tokenInfo = formattingScanner.isOnEOF() ? formattingScanner.readEOFTokenRange() : formattingScanner.isOnToken() ? formattingScanner.readTokenInfo(enclosingNode).token : undefined; - if (token) { + if (tokenInfo) { + const parent = findPrecedingToken(tokenInfo.end, sourceFile, enclosingNode)?.parent || previousParent!; processPair( - token, - sourceFile.getLineAndCharacterOfPosition(token.pos).line, - enclosingNode, + tokenInfo, + sourceFile.getLineAndCharacterOfPosition(tokenInfo.pos).line, + parent, previousRange, previousRangeStartLine!, previousParent!, - enclosingNode, + parent, /*dynamicIndentation*/ undefined); } } diff --git a/src/services/formatting/smartIndenter.ts b/src/services/formatting/smartIndenter.ts index da74c36afcb..fc65d3581bd 100644 --- a/src/services/formatting/smartIndenter.ts +++ b/src/services/formatting/smartIndenter.ts @@ -55,7 +55,28 @@ namespace ts.formatting { // indentation is first non-whitespace character in a previous line // for block indentation, we should look for a line which contains something that's not // whitespace. - if (options.indentStyle === IndentStyle.Block) { + const currentToken = getTokenAtPosition(sourceFile, position); + // for object literal, we want to the indentation work like block + // if { starts in any position (can be in the middle of line) + // the following indentation should treat { as starting of that line (including leading whitespace) + // ``` + // const a: { x: undefined, y: undefined } = {} // leading 4 whitespaces and { starts in the middle of line + // -> + // const a: { x: undefined, y: undefined } = { + // x: undefined, + // y: undefined, + // } + // --------------------- + // const a: {x : undefined, y: undefined } = + // {} + // -> + // const a: { x: undefined, y: undefined } = + // { // leading 5 whitespaces and { starts at 6 column + // x: undefined, + // y: undefined, + // } + // ``` + if (options.indentStyle === IndentStyle.Block || currentToken.kind === SyntaxKind.OpenBraceToken) { return getBlockIndent(sourceFile, position, options); } diff --git a/src/services/inlayHints.ts b/src/services/inlayHints.ts index f36b6e7d087..110e9718405 100644 --- a/src/services/inlayHints.ts +++ b/src/services/inlayHints.ts @@ -279,7 +279,7 @@ namespace ts.InlayHints { continue; } - addTypeHints(typeDisplayString, param.name.end); + addTypeHints(typeDisplayString, param.questionToken ? param.questionToken.end : param.name.end); } } diff --git a/src/services/jsDoc.ts b/src/services/jsDoc.ts index 2e6f3b04ddd..43600422a5c 100644 --- a/src/services/jsDoc.ts +++ b/src/services/jsDoc.ts @@ -152,23 +152,14 @@ namespace ts.JsDoc { function getDisplayPartsFromComment(comment: string | readonly JSDocComment[], checker: TypeChecker | undefined): SymbolDisplayPart[] { if (typeof comment === "string") { - return [textPart(skipSeparatorFromComment(comment))]; + return [textPart(comment)]; } return flatMap( comment, - node => node.kind === SyntaxKind.JSDocText ? [textPart(skipSeparatorFromComment(node.text))] : buildLinkParts(node, checker) + node => node.kind === SyntaxKind.JSDocText ? [textPart(node.text)] : buildLinkParts(node, checker) ) as SymbolDisplayPart[]; } - function skipSeparatorFromComment(text: string) { - let pos = 0; - if (text.charCodeAt(pos++) === CharacterCodes.minus) { - while (pos < text.length && text.charCodeAt(pos) === CharacterCodes.space) pos++; - return text.slice(pos); - } - return text; - } - function getCommentDisplayParts(tag: JSDocTag, checker?: TypeChecker): SymbolDisplayPart[] | undefined { const { comment, kind } = tag; const namePart = getTagNameDisplayPart(kind); diff --git a/src/services/refactors/convertImport.ts b/src/services/refactors/convertImport.ts index 3589e3006c1..01333162abb 100644 --- a/src/services/refactors/convertImport.ts +++ b/src/services/refactors/convertImport.ts @@ -79,22 +79,25 @@ namespace ts.refactor { if (importClause.namedBindings.kind === SyntaxKind.NamespaceImport) { return { convertTo: ImportKind.Named, import: importClause.namedBindings }; } - const compilerOptions = context.program.getCompilerOptions(); - const shouldUseDefault = getAllowSyntheticDefaultImports(compilerOptions) - && isExportEqualsModule(importClause.parent.moduleSpecifier, context.program.getTypeChecker()); + const shouldUseDefault = getShouldUseDefault(context.program, importClause); return shouldUseDefault ? { convertTo: ImportKind.Default, import: importClause.namedBindings } : { convertTo: ImportKind.Namespace, import: importClause.namedBindings }; } + function getShouldUseDefault(program: Program, importClause: ImportClause) { + return getAllowSyntheticDefaultImports(program.getCompilerOptions()) + && isExportEqualsModule(importClause.parent.moduleSpecifier, program.getTypeChecker()); + } + function doChange(sourceFile: SourceFile, program: Program, changes: textChanges.ChangeTracker, info: ImportConversionInfo): void { const checker = program.getTypeChecker(); if (info.convertTo === ImportKind.Named) { doChangeNamespaceToNamed(sourceFile, checker, changes, info.import, getAllowSyntheticDefaultImports(program.getCompilerOptions())); } else { - doChangeNamedToNamespaceOrDefault(sourceFile, checker, changes, info.import, info.convertTo === ImportKind.Default); + doChangeNamedToNamespaceOrDefault(sourceFile, program, changes, info.import, info.convertTo === ImportKind.Default); } } @@ -153,7 +156,8 @@ namespace ts.refactor { return isPropertyAccessExpression(propertyAccessOrQualifiedName) ? propertyAccessOrQualifiedName.expression : propertyAccessOrQualifiedName.left; } - function doChangeNamedToNamespaceOrDefault(sourceFile: SourceFile, checker: TypeChecker, changes: textChanges.ChangeTracker, toConvert: NamedImports, shouldUseDefault: boolean) { + export function doChangeNamedToNamespaceOrDefault(sourceFile: SourceFile, program: Program, changes: textChanges.ChangeTracker, toConvert: NamedImports, shouldUseDefault = getShouldUseDefault(program, toConvert.parent)): void { + const checker = program.getTypeChecker(); const importDecl = toConvert.parent.parent; const { moduleSpecifier } = importDecl; diff --git a/src/services/refactors/extractSymbol.ts b/src/services/refactors/extractSymbol.ts index 37310c041e8..36571bbf1c1 100644 --- a/src/services/refactors/extractSymbol.ts +++ b/src/services/refactors/extractSymbol.ts @@ -1136,7 +1136,9 @@ namespace ts.refactor.extractSymbol { // Make a unique name for the extracted variable const file = scope.getSourceFile(); - const localNameText = getUniqueName(isClassLike(scope) ? "newProperty" : "newLocal", file); + const localNameText = isPropertyAccessExpression(node) && !isClassLike(scope) && !checker.resolveName(node.name.text, node, SymbolFlags.Value, /*excludeGlobals*/ false) && !isPrivateIdentifier(node.name) && !isKeyword(node.name.originalKeywordKind!) + ? node.name.text + : getUniqueName(isClassLike(scope) ? "newProperty" : "newLocal", file); const isJS = isInJSFile(scope); let variableType = isJS || !checker.isContextSensitive(node) diff --git a/src/services/refactors/extractType.ts b/src/services/refactors/extractType.ts index 0e16def63fe..c785160ad80 100644 --- a/src/services/refactors/extractType.ts +++ b/src/services/refactors/extractType.ts @@ -203,7 +203,7 @@ namespace ts.refactor { /* decorators */ undefined, /* modifiers */ undefined, name, - typeParameters.map(id => factory.updateTypeParameterDeclaration(id, id.name, id.constraint, /* defaultType */ undefined)), + typeParameters.map(id => factory.updateTypeParameterDeclaration(id, id.modifiers, id.name, id.constraint, /* defaultType */ undefined)), selection ); changes.insertNodeBefore(file, firstStatement, ignoreSourceNewlines(newTypeNode), /* blankLineBetween */ true); @@ -237,7 +237,7 @@ namespace ts.refactor { const templates: JSDocTemplateTag[] = []; forEach(typeParameters, typeParameter => { const constraint = getEffectiveConstraintOfTypeParameter(typeParameter); - const parameter = factory.createTypeParameterDeclaration(typeParameter.name); + const parameter = factory.createTypeParameterDeclaration(/*modifiers*/ undefined, typeParameter.name); const template = factory.createJSDocTemplateTag( factory.createIdentifier("template"), constraint && cast(constraint, isJSDocTypeExpression), diff --git a/src/services/services.ts b/src/services/services.ts index 503482d63c7..efb31f25797 100644 --- a/src/services/services.ts +++ b/src/services/services.ts @@ -1004,9 +1004,11 @@ namespace ts { // Initialize the list with the root file names const rootFileNames = host.getScriptFileNames(); + tracing?.push(tracing.Phase.Session, "initializeHostCache", { count: rootFileNames.length }); for (const fileName of rootFileNames) { this.createEntry(fileName, toPath(fileName, this.currentDirectory, getCanonicalFileName)); } + tracing?.pop(); } private createEntry(fileName: string, path: Path) { diff --git a/src/services/shims.ts b/src/services/shims.ts index 90890e70ed6..cc09074aad5 100644 --- a/src/services/shims.ts +++ b/src/services/shims.ts @@ -554,7 +554,7 @@ namespace ts { } } - function simpleForwardCall(logger: Logger, actionDescription: string, action: () => {}, logPerformance: boolean): {} { + function simpleForwardCall(logger: Logger, actionDescription: string, action: () => unknown, logPerformance: boolean): unknown { let start: number | undefined; if (logPerformance) { logger.log(actionDescription); diff --git a/src/services/textChanges.ts b/src/services/textChanges.ts index dc2918572d0..a4e0557222d 100644 --- a/src/services/textChanges.ts +++ b/src/services/textChanges.ts @@ -116,10 +116,6 @@ namespace ts.textChanges { * Text of inserted node will be formatted with this delta, otherwise delta will be inferred from the new node kind */ delta?: number; - /** - * Do not trim leading white spaces in the edit range - */ - preserveLeadingWhitespace?: boolean; } export interface ReplaceWithMultipleNodesOptions extends InsertNodeOptions { @@ -492,7 +488,7 @@ namespace ts.textChanges { } const startPosition = getPrecedingNonSpaceCharacterPosition(sourceFile.text, fnStart - 1); const indent = sourceFile.text.slice(startPosition, fnStart); - this.insertNodeAt(sourceFile, fnStart, tag, { preserveLeadingWhitespace: false, suffix: this.newLineCharacter + indent }); + this.insertNodeAt(sourceFile, fnStart, tag, { suffix: this.newLineCharacter + indent }); } private createJSDocText(sourceFile: SourceFile, node: HasJSDoc) { @@ -1068,7 +1064,7 @@ namespace ts.textChanges { ? change.nodes.map(n => removeSuffix(format(n), newLineCharacter)).join(change.options?.joiner || newLineCharacter) : format(change.node); // strip initial indentation (spaces or tabs) if text will be inserted in the middle of the line - const noIndent = (options.preserveLeadingWhitespace || options.indentation !== undefined || getLineStartPositionForPosition(pos, sourceFile) === pos) ? text : text.replace(/^\s+/, ""); + const noIndent = (options.indentation !== undefined || getLineStartPositionForPosition(pos, sourceFile) === pos) ? text : text.replace(/^\s+/, ""); return (options.prefix || "") + noIndent + ((!options.suffix || endsWith(noIndent, options.suffix)) ? "" : options.suffix); diff --git a/src/services/tsconfig.json b/src/services/tsconfig.json index 3cd21883146..cef6b913969 100644 --- a/src/services/tsconfig.json +++ b/src/services/tsconfig.json @@ -88,6 +88,7 @@ "codefixes/fixForgottenThisPropertyAccess.ts", "codefixes/fixInvalidJsxCharacters.ts", "codefixes/fixUnmatchedParameter.ts", + "codefixes/fixUnreferenceableDecoratorMetadata.ts", "codefixes/fixUnusedIdentifier.ts", "codefixes/fixUnreachableCode.ts", "codefixes/fixUnusedLabel.ts", diff --git a/src/services/utilities.ts b/src/services/utilities.ts index 88836f59c34..e20f049ab83 100644 --- a/src/services/utilities.ts +++ b/src/services/utilities.ts @@ -1256,8 +1256,10 @@ namespace ts { * Finds the rightmost token satisfying `token.end <= position`, * excluding `JsxText` tokens containing only whitespace. */ - export function findPrecedingToken(position: number, sourceFile: SourceFile, startNode?: Node, excludeJsdoc?: boolean): Node | undefined { - const result = find(startNode || sourceFile); + export function findPrecedingToken(position: number, sourceFile: SourceFileLike, startNode: Node, excludeJsdoc?: boolean): Node | undefined; + export function findPrecedingToken(position: number, sourceFile: SourceFile, startNode?: Node, excludeJsdoc?: boolean): Node | undefined; + export function findPrecedingToken(position: number, sourceFile: SourceFileLike, startNode?: Node, excludeJsdoc?: boolean): Node | undefined { + const result = find((startNode || sourceFile) as Node); Debug.assert(!(result && isWhiteSpaceOnlyJsxText(result))); return result; @@ -1322,7 +1324,7 @@ namespace ts { return isToken(n) && !isWhiteSpaceOnlyJsxText(n); } - function findRightmostToken(n: Node, sourceFile: SourceFile): Node | undefined { + function findRightmostToken(n: Node, sourceFile: SourceFileLike): Node | undefined { if (isNonWhitespaceToken(n)) { return n; } @@ -1339,7 +1341,7 @@ namespace ts { /** * Finds the rightmost child to the left of `children[exclusiveStartPosition]` which is a non-all-whitespace token or has constituent tokens. */ - function findRightmostChildNodeWithTokens(children: Node[], exclusiveStartPosition: number, sourceFile: SourceFile, parentKind: SyntaxKind): Node | undefined { + function findRightmostChildNodeWithTokens(children: Node[], exclusiveStartPosition: number, sourceFile: SourceFileLike, parentKind: SyntaxKind): Node | undefined { for (let i = exclusiveStartPosition - 1; i >= 0; i--) { const child = children[i]; diff --git a/src/testRunner/unittests/printer.ts b/src/testRunner/unittests/printer.ts index 50c776c0f9f..51e1727e7ef 100644 --- a/src/testRunner/unittests/printer.ts +++ b/src/testRunner/unittests/printer.ts @@ -267,7 +267,7 @@ namespace ts { factory.createKeywordTypeNode(SyntaxKind.AnyKeyword) ), factory.createFunctionTypeNode( - [factory.createTypeParameterDeclaration("T")], + [factory.createTypeParameterDeclaration(/*modifiers*/ undefined, "T")], [factory.createParameterDeclaration( /*decorators*/ undefined, /*modifiers*/ undefined, diff --git a/src/testRunner/unittests/programApi.ts b/src/testRunner/unittests/programApi.ts index 359dff1c034..e15ec0bf434 100644 --- a/src/testRunner/unittests/programApi.ts +++ b/src/testRunner/unittests/programApi.ts @@ -179,13 +179,13 @@ namespace ts { }); }); - describe("unittests:: programApi:: Program.getDiagnosticsProducingTypeChecker / Program.getSemanticDiagnostics", () => { + describe("unittests:: programApi:: Program.getTypeChecker / Program.getSemanticDiagnostics", () => { it("does not produce errors on `as const` it would not normally produce on the command line", () => { const main = new documents.TextDocument("/main.ts", "0 as const"); const fs = vfs.createFromFileSystem(Harness.IO, /*ignoreCase*/ false, { documents: [main], cwd: "/" }); const program = createProgram(["/main.ts"], {}, new fakes.CompilerHost(fs, { newLine: NewLineKind.LineFeed })); - const typeChecker = program.getDiagnosticsProducingTypeChecker(); + const typeChecker = program.getTypeChecker(); const sourceFile = program.getSourceFile("main.ts")!; typeChecker.getTypeAtLocation(((sourceFile.statements[0] as ExpressionStatement).expression as AsExpression).type); const diag = program.getSemanticDiagnostics(); @@ -199,7 +199,7 @@ namespace ts { const program = createProgram(["/main.ts"], {}, new fakes.CompilerHost(fs, { newLine: NewLineKind.LineFeed })); const sourceFile = program.getSourceFile("main.ts")!; - const typeChecker = program.getDiagnosticsProducingTypeChecker(); + const typeChecker = program.getTypeChecker(); typeChecker.getSymbolAtLocation((sourceFile.statements[0] as ImportDeclaration).moduleSpecifier); assert.isEmpty(program.getSemanticDiagnostics()); }); diff --git a/src/testRunner/unittests/services/extract/constants.ts b/src/testRunner/unittests/services/extract/constants.ts index d9cd5010d5b..05c3aa5ac52 100644 --- a/src/testRunner/unittests/services/extract/constants.ts +++ b/src/testRunner/unittests/services/extract/constants.ts @@ -279,6 +279,19 @@ switch (1) { break; } `); + + testExtractConstant("extractConstant_PropertyName", + `[#|x.y|].z();`); + + testExtractConstant("extractConstant_PropertyName_ExistingName", + `let y; +[#|x.y|].z();`); + + testExtractConstant("extractConstant_PropertyName_Keyword", + `[#|x.if|].z();`); + + testExtractConstant("extractConstant_PropertyName_PrivateIdentifierKeyword", + `[#|this.#if|].z();`); }); function testExtractConstant(caption: string, text: string) { diff --git a/src/testRunner/unittests/tsserver/jsdocTag.ts b/src/testRunner/unittests/tsserver/jsdocTag.ts index 14cdc9df7c4..7699c107586 100644 --- a/src/testRunner/unittests/tsserver/jsdocTag.ts +++ b/src/testRunner/unittests/tsserver/jsdocTag.ts @@ -386,11 +386,11 @@ x(1)` displayPartsForJSDoc: false, tags: [{ name: "param", - text: "y {@link C}" + text: "y - {@link C}" }], documentation: [{ kind: "text", - text: "" + text: "- " }, { kind: "link", text: "{@link " @@ -425,7 +425,7 @@ x(1)` text: " " }, { kind: "text", - text: "" + text: "- " }, { kind: "link", text: "{@link " @@ -461,11 +461,11 @@ x(1)` displayPartsForJSDoc: false, tags: [{ name: "param", - text: "y {@link C}" + text: "y - {@link C}" }], documentation: [{ kind: "text", - text: "" + text: "- " }, { kind: "link", text: "{@link " @@ -496,7 +496,7 @@ x(1)` text: " " }, { kind: "text", - text: "" + text: "- " }, { kind: "link", text: "{@link " @@ -610,7 +610,7 @@ foo` text: " " }, { kind: "text", - text: "see " + text: "- see " }, { kind: "link", text: "{@link " @@ -641,7 +641,7 @@ foo` displayPartsForJSDoc: false, tags: [{ name: "param", - text: "x see {@link C}", + text: "x - see {@link C}", }], }); }); @@ -659,7 +659,7 @@ foo` text: " " }, { kind: "text", - text: "see " + text: "- see " }, { kind: "link", text: "{@link " @@ -686,7 +686,7 @@ foo` displayPartsForJSDoc: false, tags: [{ name: "param", - text: "x see {@link C}", + text: "x - see {@link C}", }], }); }); diff --git a/src/testRunner/unittests/tsserver/languageService.ts b/src/testRunner/unittests/tsserver/languageService.ts index 86d426664df..8e7bf0eedcd 100644 --- a/src/testRunner/unittests/tsserver/languageService.ts +++ b/src/testRunner/unittests/tsserver/languageService.ts @@ -1,5 +1,5 @@ namespace ts.projectSystem { - describe("unittests:: tsserver:: Language service", () => { + describe("unittests:: tsserver:: languageService", () => { it("should work correctly on case-sensitive file systems", () => { const lib = { path: "/a/Lib/lib.d.ts", @@ -15,5 +15,54 @@ namespace ts.projectSystem { projectService.checkNumberOfProjects({ inferredProjects: 1 }); projectService.inferredProjects[0].getLanguageService().getProgram(); }); + + it("should support multiple projects with the same file under differing `paths` settings", () => { + const files = [ + { + path: "/project/shared.ts", + content: Utils.dedent` + import {foo_a} from "foo"; + ` + }, + { + path: `/project/a/tsconfig.json`, + content: `{ "compilerOptions": { "paths": { "foo": ["./foo.d.ts"] } }, "files": ["./index.ts", "./foo.d.ts"] }` + }, + { + path: `/project/a/foo.d.ts`, + content: Utils.dedent` + export const foo_a = 1; + ` + }, + { + path: "/project/a/index.ts", + content: `import "../shared";` + }, + { + path: `/project/b/tsconfig.json`, + content: `{ "compilerOptions": { "paths": { "foo": ["./foo.d.ts"] } }, "files": ["./index.ts", "./foo.d.ts"] }` + }, + { + path: `/project/b/foo.d.ts`, + content: Utils.dedent` + export const foo_b = 1; + ` + }, + { + path: "/project/b/index.ts", + content: `import "../shared";` + } + ]; + + const host = createServerHost(files, { executingFilePath: "/project/tsc.js", useCaseSensitiveFileNames: true }); + const projectService = createProjectService(host); + projectService.openClientFile(files[3].path); + projectService.openClientFile(files[6].path); + projectService.checkNumberOfProjects({ configuredProjects: 2 }); + const proj1Diags = projectService.configuredProjects.get(files[1].path)!.getLanguageService().getProgram()!.getSemanticDiagnostics(); + Debug.assertEqual(proj1Diags.length, 0); + const proj2Diags = projectService.configuredProjects.get(files[4].path)!.getLanguageService().getProgram()!.getSemanticDiagnostics(); + Debug.assertEqual(proj2Diags.length, 1); + }); }); } diff --git a/src/testRunner/unittests/tsserver/projectReferencesSourcemap.ts b/src/testRunner/unittests/tsserver/projectReferencesSourcemap.ts index d50f879a60d..e49522f7dc9 100644 --- a/src/testRunner/unittests/tsserver/projectReferencesSourcemap.ts +++ b/src/testRunner/unittests/tsserver/projectReferencesSourcemap.ts @@ -271,7 +271,7 @@ fn5(); }); } - interface Action { + interface Action { reqName: string; request: Partial; expectedResponse: Response; diff --git a/src/testRunner/unittests/tsserver/rename.ts b/src/testRunner/unittests/tsserver/rename.ts index a30eb895f09..6c0af5688da 100644 --- a/src/testRunner/unittests/tsserver/rename.ts +++ b/src/testRunner/unittests/tsserver/rename.ts @@ -174,6 +174,43 @@ namespace ts.projectSystem { }); }); + it("export default anonymous function works with prefixText and suffixText when disabled", () => { + const aTs: File = { path: "/a.ts", content: "export default function() {}" }; + const bTs: File = { path: "/b.ts", content: `import aTest from "./a"; function test() { return aTest(); }` }; + + const session = createSession(createServerHost([aTs, bTs])); + openFilesForSession([bTs], session); + + session.getProjectService().setHostConfiguration({ preferences: { providePrefixAndSuffixTextForRename: false } }); + const response1 = executeSessionRequest(session, protocol.CommandTypes.Rename, protocolFileLocationFromSubstring(bTs, "aTest(")); + assert.deepEqual(response1, { + info: { + canRename: true, + fileToRename: undefined, + displayName: "aTest", + fullDisplayName: "aTest", + kind: ScriptElementKind.alias, + kindModifiers: "export", + triggerSpan: protocolTextSpanFromSubstring(bTs.content, "aTest", { index: 1 }) + }, + locs: [{ + file: bTs.path, + locs: [ + protocolRenameSpanFromSubstring({ + fileText: bTs.content, + text: "aTest", + contextText: `import aTest from "./a";` + }), + protocolRenameSpanFromSubstring({ + fileText: bTs.content, + text: "aTest", + options: { index: 1 }, + }) + ] + }], + }); + }); + it("rename behavior is based on file of rename initiation", () => { const aTs: File = { path: "/a.ts", content: "const x = 1; export { x };" }; const bTs: File = { path: "/b.ts", content: `import { x } from "./a"; const y = x + 1;` }; diff --git a/tests/baselines/reference/api/tsserverlibrary.d.ts b/tests/baselines/reference/api/tsserverlibrary.d.ts index 0c0732c830a..edec6392836 100644 --- a/tests/baselines/reference/api/tsserverlibrary.d.ts +++ b/tests/baselines/reference/api/tsserverlibrary.d.ts @@ -249,218 +249,219 @@ declare namespace ts { ModuleKeyword = 141, NamespaceKeyword = 142, NeverKeyword = 143, - ReadonlyKeyword = 144, - RequireKeyword = 145, - NumberKeyword = 146, - ObjectKeyword = 147, - SetKeyword = 148, - StringKeyword = 149, - SymbolKeyword = 150, - TypeKeyword = 151, - UndefinedKeyword = 152, - UniqueKeyword = 153, - UnknownKeyword = 154, - FromKeyword = 155, - GlobalKeyword = 156, - BigIntKeyword = 157, - OverrideKeyword = 158, - OfKeyword = 159, - QualifiedName = 160, - ComputedPropertyName = 161, - TypeParameter = 162, - Parameter = 163, - Decorator = 164, - PropertySignature = 165, - PropertyDeclaration = 166, - MethodSignature = 167, - MethodDeclaration = 168, - ClassStaticBlockDeclaration = 169, - Constructor = 170, - GetAccessor = 171, - SetAccessor = 172, - CallSignature = 173, - ConstructSignature = 174, - IndexSignature = 175, - TypePredicate = 176, - TypeReference = 177, - FunctionType = 178, - ConstructorType = 179, - TypeQuery = 180, - TypeLiteral = 181, - ArrayType = 182, - TupleType = 183, - OptionalType = 184, - RestType = 185, - UnionType = 186, - IntersectionType = 187, - ConditionalType = 188, - InferType = 189, - ParenthesizedType = 190, - ThisType = 191, - TypeOperator = 192, - IndexedAccessType = 193, - MappedType = 194, - LiteralType = 195, - NamedTupleMember = 196, - TemplateLiteralType = 197, - TemplateLiteralTypeSpan = 198, - ImportType = 199, - ObjectBindingPattern = 200, - ArrayBindingPattern = 201, - BindingElement = 202, - ArrayLiteralExpression = 203, - ObjectLiteralExpression = 204, - PropertyAccessExpression = 205, - ElementAccessExpression = 206, - CallExpression = 207, - NewExpression = 208, - TaggedTemplateExpression = 209, - TypeAssertionExpression = 210, - ParenthesizedExpression = 211, - FunctionExpression = 212, - ArrowFunction = 213, - DeleteExpression = 214, - TypeOfExpression = 215, - VoidExpression = 216, - AwaitExpression = 217, - PrefixUnaryExpression = 218, - PostfixUnaryExpression = 219, - BinaryExpression = 220, - ConditionalExpression = 221, - TemplateExpression = 222, - YieldExpression = 223, - SpreadElement = 224, - ClassExpression = 225, - OmittedExpression = 226, - ExpressionWithTypeArguments = 227, - AsExpression = 228, - NonNullExpression = 229, - MetaProperty = 230, - SyntheticExpression = 231, - TemplateSpan = 232, - SemicolonClassElement = 233, - Block = 234, - EmptyStatement = 235, - VariableStatement = 236, - ExpressionStatement = 237, - IfStatement = 238, - DoStatement = 239, - WhileStatement = 240, - ForStatement = 241, - ForInStatement = 242, - ForOfStatement = 243, - ContinueStatement = 244, - BreakStatement = 245, - ReturnStatement = 246, - WithStatement = 247, - SwitchStatement = 248, - LabeledStatement = 249, - ThrowStatement = 250, - TryStatement = 251, - DebuggerStatement = 252, - VariableDeclaration = 253, - VariableDeclarationList = 254, - FunctionDeclaration = 255, - ClassDeclaration = 256, - InterfaceDeclaration = 257, - TypeAliasDeclaration = 258, - EnumDeclaration = 259, - ModuleDeclaration = 260, - ModuleBlock = 261, - CaseBlock = 262, - NamespaceExportDeclaration = 263, - ImportEqualsDeclaration = 264, - ImportDeclaration = 265, - ImportClause = 266, - NamespaceImport = 267, - NamedImports = 268, - ImportSpecifier = 269, - ExportAssignment = 270, - ExportDeclaration = 271, - NamedExports = 272, - NamespaceExport = 273, - ExportSpecifier = 274, - MissingDeclaration = 275, - ExternalModuleReference = 276, - JsxElement = 277, - JsxSelfClosingElement = 278, - JsxOpeningElement = 279, - JsxClosingElement = 280, - JsxFragment = 281, - JsxOpeningFragment = 282, - JsxClosingFragment = 283, - JsxAttribute = 284, - JsxAttributes = 285, - JsxSpreadAttribute = 286, - JsxExpression = 287, - CaseClause = 288, - DefaultClause = 289, - HeritageClause = 290, - CatchClause = 291, - AssertClause = 292, - AssertEntry = 293, - ImportTypeAssertionContainer = 294, - PropertyAssignment = 295, - ShorthandPropertyAssignment = 296, - SpreadAssignment = 297, - EnumMember = 298, - UnparsedPrologue = 299, - UnparsedPrepend = 300, - UnparsedText = 301, - UnparsedInternalText = 302, - UnparsedSyntheticReference = 303, - SourceFile = 304, - Bundle = 305, - UnparsedSource = 306, - InputFiles = 307, - JSDocTypeExpression = 308, - JSDocNameReference = 309, - JSDocMemberName = 310, - JSDocAllType = 311, - JSDocUnknownType = 312, - JSDocNullableType = 313, - JSDocNonNullableType = 314, - JSDocOptionalType = 315, - JSDocFunctionType = 316, - JSDocVariadicType = 317, - JSDocNamepathType = 318, + OutKeyword = 144, + ReadonlyKeyword = 145, + RequireKeyword = 146, + NumberKeyword = 147, + ObjectKeyword = 148, + SetKeyword = 149, + StringKeyword = 150, + SymbolKeyword = 151, + TypeKeyword = 152, + UndefinedKeyword = 153, + UniqueKeyword = 154, + UnknownKeyword = 155, + FromKeyword = 156, + GlobalKeyword = 157, + BigIntKeyword = 158, + OverrideKeyword = 159, + OfKeyword = 160, + QualifiedName = 161, + ComputedPropertyName = 162, + TypeParameter = 163, + Parameter = 164, + Decorator = 165, + PropertySignature = 166, + PropertyDeclaration = 167, + MethodSignature = 168, + MethodDeclaration = 169, + ClassStaticBlockDeclaration = 170, + Constructor = 171, + GetAccessor = 172, + SetAccessor = 173, + CallSignature = 174, + ConstructSignature = 175, + IndexSignature = 176, + TypePredicate = 177, + TypeReference = 178, + FunctionType = 179, + ConstructorType = 180, + TypeQuery = 181, + TypeLiteral = 182, + ArrayType = 183, + TupleType = 184, + OptionalType = 185, + RestType = 186, + UnionType = 187, + IntersectionType = 188, + ConditionalType = 189, + InferType = 190, + ParenthesizedType = 191, + ThisType = 192, + TypeOperator = 193, + IndexedAccessType = 194, + MappedType = 195, + LiteralType = 196, + NamedTupleMember = 197, + TemplateLiteralType = 198, + TemplateLiteralTypeSpan = 199, + ImportType = 200, + ObjectBindingPattern = 201, + ArrayBindingPattern = 202, + BindingElement = 203, + ArrayLiteralExpression = 204, + ObjectLiteralExpression = 205, + PropertyAccessExpression = 206, + ElementAccessExpression = 207, + CallExpression = 208, + NewExpression = 209, + TaggedTemplateExpression = 210, + TypeAssertionExpression = 211, + ParenthesizedExpression = 212, + FunctionExpression = 213, + ArrowFunction = 214, + DeleteExpression = 215, + TypeOfExpression = 216, + VoidExpression = 217, + AwaitExpression = 218, + PrefixUnaryExpression = 219, + PostfixUnaryExpression = 220, + BinaryExpression = 221, + ConditionalExpression = 222, + TemplateExpression = 223, + YieldExpression = 224, + SpreadElement = 225, + ClassExpression = 226, + OmittedExpression = 227, + ExpressionWithTypeArguments = 228, + AsExpression = 229, + NonNullExpression = 230, + MetaProperty = 231, + SyntheticExpression = 232, + TemplateSpan = 233, + SemicolonClassElement = 234, + Block = 235, + EmptyStatement = 236, + VariableStatement = 237, + ExpressionStatement = 238, + IfStatement = 239, + DoStatement = 240, + WhileStatement = 241, + ForStatement = 242, + ForInStatement = 243, + ForOfStatement = 244, + ContinueStatement = 245, + BreakStatement = 246, + ReturnStatement = 247, + WithStatement = 248, + SwitchStatement = 249, + LabeledStatement = 250, + ThrowStatement = 251, + TryStatement = 252, + DebuggerStatement = 253, + VariableDeclaration = 254, + VariableDeclarationList = 255, + FunctionDeclaration = 256, + ClassDeclaration = 257, + InterfaceDeclaration = 258, + TypeAliasDeclaration = 259, + EnumDeclaration = 260, + ModuleDeclaration = 261, + ModuleBlock = 262, + CaseBlock = 263, + NamespaceExportDeclaration = 264, + ImportEqualsDeclaration = 265, + ImportDeclaration = 266, + ImportClause = 267, + NamespaceImport = 268, + NamedImports = 269, + ImportSpecifier = 270, + ExportAssignment = 271, + ExportDeclaration = 272, + NamedExports = 273, + NamespaceExport = 274, + ExportSpecifier = 275, + MissingDeclaration = 276, + ExternalModuleReference = 277, + JsxElement = 278, + JsxSelfClosingElement = 279, + JsxOpeningElement = 280, + JsxClosingElement = 281, + JsxFragment = 282, + JsxOpeningFragment = 283, + JsxClosingFragment = 284, + JsxAttribute = 285, + JsxAttributes = 286, + JsxSpreadAttribute = 287, + JsxExpression = 288, + CaseClause = 289, + DefaultClause = 290, + HeritageClause = 291, + CatchClause = 292, + AssertClause = 293, + AssertEntry = 294, + ImportTypeAssertionContainer = 295, + PropertyAssignment = 296, + ShorthandPropertyAssignment = 297, + SpreadAssignment = 298, + EnumMember = 299, + UnparsedPrologue = 300, + UnparsedPrepend = 301, + UnparsedText = 302, + UnparsedInternalText = 303, + UnparsedSyntheticReference = 304, + SourceFile = 305, + Bundle = 306, + UnparsedSource = 307, + InputFiles = 308, + JSDocTypeExpression = 309, + JSDocNameReference = 310, + JSDocMemberName = 311, + JSDocAllType = 312, + JSDocUnknownType = 313, + JSDocNullableType = 314, + JSDocNonNullableType = 315, + JSDocOptionalType = 316, + JSDocFunctionType = 317, + JSDocVariadicType = 318, + JSDocNamepathType = 319, /** @deprecated Use SyntaxKind.JSDoc */ - JSDocComment = 319, - JSDocText = 320, - JSDocTypeLiteral = 321, - JSDocSignature = 322, - JSDocLink = 323, - JSDocLinkCode = 324, - JSDocLinkPlain = 325, - JSDocTag = 326, - JSDocAugmentsTag = 327, - JSDocImplementsTag = 328, - JSDocAuthorTag = 329, - JSDocDeprecatedTag = 330, - JSDocClassTag = 331, - JSDocPublicTag = 332, - JSDocPrivateTag = 333, - JSDocProtectedTag = 334, - JSDocReadonlyTag = 335, - JSDocOverrideTag = 336, - JSDocCallbackTag = 337, - JSDocEnumTag = 338, - JSDocParameterTag = 339, - JSDocReturnTag = 340, - JSDocThisTag = 341, - JSDocTypeTag = 342, - JSDocTemplateTag = 343, - JSDocTypedefTag = 344, - JSDocSeeTag = 345, - JSDocPropertyTag = 346, - SyntaxList = 347, - NotEmittedStatement = 348, - PartiallyEmittedExpression = 349, - CommaListExpression = 350, - MergeDeclarationMarker = 351, - EndOfDeclarationMarker = 352, - SyntheticReferenceExpression = 353, - Count = 354, + JSDocComment = 320, + JSDocText = 321, + JSDocTypeLiteral = 322, + JSDocSignature = 323, + JSDocLink = 324, + JSDocLinkCode = 325, + JSDocLinkPlain = 326, + JSDocTag = 327, + JSDocAugmentsTag = 328, + JSDocImplementsTag = 329, + JSDocAuthorTag = 330, + JSDocDeprecatedTag = 331, + JSDocClassTag = 332, + JSDocPublicTag = 333, + JSDocPrivateTag = 334, + JSDocProtectedTag = 335, + JSDocReadonlyTag = 336, + JSDocOverrideTag = 337, + JSDocCallbackTag = 338, + JSDocEnumTag = 339, + JSDocParameterTag = 340, + JSDocReturnTag = 341, + JSDocThisTag = 342, + JSDocTypeTag = 343, + JSDocTemplateTag = 344, + JSDocTypedefTag = 345, + JSDocSeeTag = 346, + JSDocPropertyTag = 347, + SyntaxList = 348, + NotEmittedStatement = 349, + PartiallyEmittedExpression = 350, + CommaListExpression = 351, + MergeDeclarationMarker = 352, + EndOfDeclarationMarker = 353, + SyntheticReferenceExpression = 354, + Count = 355, FirstAssignment = 63, LastAssignment = 78, FirstCompoundAssignment = 64, @@ -468,15 +469,15 @@ declare namespace ts { FirstReservedWord = 81, LastReservedWord = 116, FirstKeyword = 81, - LastKeyword = 159, + LastKeyword = 160, FirstFutureReservedWord = 117, LastFutureReservedWord = 125, - FirstTypeNode = 176, - LastTypeNode = 199, + FirstTypeNode = 177, + LastTypeNode = 200, FirstPunctuation = 18, LastPunctuation = 78, FirstToken = 0, - LastToken = 159, + LastToken = 160, FirstTriviaToken = 2, LastTriviaToken = 7, FirstLiteralToken = 8, @@ -485,21 +486,21 @@ declare namespace ts { LastTemplateToken = 17, FirstBinaryOperator = 29, LastBinaryOperator = 78, - FirstStatement = 236, - LastStatement = 252, - FirstNode = 160, - FirstJSDocNode = 308, - LastJSDocNode = 346, - FirstJSDocTagNode = 326, - LastJSDocTagNode = 346, - JSDoc = 319 + FirstStatement = 237, + LastStatement = 253, + FirstNode = 161, + FirstJSDocNode = 309, + LastJSDocNode = 347, + FirstJSDocTagNode = 327, + LastJSDocTagNode = 347, + JSDoc = 320 } export type TriviaSyntaxKind = SyntaxKind.SingleLineCommentTrivia | SyntaxKind.MultiLineCommentTrivia | SyntaxKind.NewLineTrivia | SyntaxKind.WhitespaceTrivia | SyntaxKind.ShebangTrivia | SyntaxKind.ConflictMarkerTrivia; export type LiteralSyntaxKind = SyntaxKind.NumericLiteral | SyntaxKind.BigIntLiteral | SyntaxKind.StringLiteral | SyntaxKind.JsxText | SyntaxKind.JsxTextAllWhiteSpaces | SyntaxKind.RegularExpressionLiteral | SyntaxKind.NoSubstitutionTemplateLiteral; export type PseudoLiteralSyntaxKind = SyntaxKind.TemplateHead | SyntaxKind.TemplateMiddle | SyntaxKind.TemplateTail; export type PunctuationSyntaxKind = SyntaxKind.OpenBraceToken | SyntaxKind.CloseBraceToken | SyntaxKind.OpenParenToken | SyntaxKind.CloseParenToken | SyntaxKind.OpenBracketToken | SyntaxKind.CloseBracketToken | SyntaxKind.DotToken | SyntaxKind.DotDotDotToken | SyntaxKind.SemicolonToken | SyntaxKind.CommaToken | SyntaxKind.QuestionDotToken | SyntaxKind.LessThanToken | SyntaxKind.LessThanSlashToken | SyntaxKind.GreaterThanToken | SyntaxKind.LessThanEqualsToken | SyntaxKind.GreaterThanEqualsToken | SyntaxKind.EqualsEqualsToken | SyntaxKind.ExclamationEqualsToken | SyntaxKind.EqualsEqualsEqualsToken | SyntaxKind.ExclamationEqualsEqualsToken | SyntaxKind.EqualsGreaterThanToken | SyntaxKind.PlusToken | SyntaxKind.MinusToken | SyntaxKind.AsteriskToken | SyntaxKind.AsteriskAsteriskToken | SyntaxKind.SlashToken | SyntaxKind.PercentToken | SyntaxKind.PlusPlusToken | SyntaxKind.MinusMinusToken | SyntaxKind.LessThanLessThanToken | SyntaxKind.GreaterThanGreaterThanToken | SyntaxKind.GreaterThanGreaterThanGreaterThanToken | SyntaxKind.AmpersandToken | SyntaxKind.BarToken | SyntaxKind.CaretToken | SyntaxKind.ExclamationToken | SyntaxKind.TildeToken | SyntaxKind.AmpersandAmpersandToken | SyntaxKind.BarBarToken | SyntaxKind.QuestionQuestionToken | SyntaxKind.QuestionToken | SyntaxKind.ColonToken | SyntaxKind.AtToken | SyntaxKind.BacktickToken | SyntaxKind.HashToken | SyntaxKind.EqualsToken | SyntaxKind.PlusEqualsToken | SyntaxKind.MinusEqualsToken | SyntaxKind.AsteriskEqualsToken | SyntaxKind.AsteriskAsteriskEqualsToken | SyntaxKind.SlashEqualsToken | SyntaxKind.PercentEqualsToken | SyntaxKind.LessThanLessThanEqualsToken | SyntaxKind.GreaterThanGreaterThanEqualsToken | SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken | SyntaxKind.AmpersandEqualsToken | SyntaxKind.BarEqualsToken | SyntaxKind.CaretEqualsToken; - export type KeywordSyntaxKind = SyntaxKind.AbstractKeyword | SyntaxKind.AnyKeyword | SyntaxKind.AsKeyword | SyntaxKind.AssertsKeyword | SyntaxKind.AssertKeyword | SyntaxKind.AsyncKeyword | SyntaxKind.AwaitKeyword | SyntaxKind.BigIntKeyword | SyntaxKind.BooleanKeyword | SyntaxKind.BreakKeyword | SyntaxKind.CaseKeyword | SyntaxKind.CatchKeyword | SyntaxKind.ClassKeyword | SyntaxKind.ConstKeyword | SyntaxKind.ConstructorKeyword | SyntaxKind.ContinueKeyword | SyntaxKind.DebuggerKeyword | SyntaxKind.DeclareKeyword | SyntaxKind.DefaultKeyword | SyntaxKind.DeleteKeyword | SyntaxKind.DoKeyword | SyntaxKind.ElseKeyword | SyntaxKind.EnumKeyword | SyntaxKind.ExportKeyword | SyntaxKind.ExtendsKeyword | SyntaxKind.FalseKeyword | SyntaxKind.FinallyKeyword | SyntaxKind.ForKeyword | SyntaxKind.FromKeyword | SyntaxKind.FunctionKeyword | SyntaxKind.GetKeyword | SyntaxKind.GlobalKeyword | SyntaxKind.IfKeyword | SyntaxKind.ImplementsKeyword | SyntaxKind.ImportKeyword | SyntaxKind.InferKeyword | SyntaxKind.InKeyword | SyntaxKind.InstanceOfKeyword | SyntaxKind.InterfaceKeyword | SyntaxKind.IntrinsicKeyword | SyntaxKind.IsKeyword | SyntaxKind.KeyOfKeyword | SyntaxKind.LetKeyword | SyntaxKind.ModuleKeyword | SyntaxKind.NamespaceKeyword | SyntaxKind.NeverKeyword | SyntaxKind.NewKeyword | SyntaxKind.NullKeyword | SyntaxKind.NumberKeyword | SyntaxKind.ObjectKeyword | SyntaxKind.OfKeyword | SyntaxKind.PackageKeyword | SyntaxKind.PrivateKeyword | SyntaxKind.ProtectedKeyword | SyntaxKind.PublicKeyword | SyntaxKind.ReadonlyKeyword | SyntaxKind.OverrideKeyword | SyntaxKind.RequireKeyword | SyntaxKind.ReturnKeyword | SyntaxKind.SetKeyword | SyntaxKind.StaticKeyword | SyntaxKind.StringKeyword | SyntaxKind.SuperKeyword | SyntaxKind.SwitchKeyword | SyntaxKind.SymbolKeyword | SyntaxKind.ThisKeyword | SyntaxKind.ThrowKeyword | SyntaxKind.TrueKeyword | SyntaxKind.TryKeyword | SyntaxKind.TypeKeyword | SyntaxKind.TypeOfKeyword | SyntaxKind.UndefinedKeyword | SyntaxKind.UniqueKeyword | SyntaxKind.UnknownKeyword | SyntaxKind.VarKeyword | SyntaxKind.VoidKeyword | SyntaxKind.WhileKeyword | SyntaxKind.WithKeyword | SyntaxKind.YieldKeyword; - export type ModifierSyntaxKind = SyntaxKind.AbstractKeyword | SyntaxKind.AsyncKeyword | SyntaxKind.ConstKeyword | SyntaxKind.DeclareKeyword | SyntaxKind.DefaultKeyword | SyntaxKind.ExportKeyword | SyntaxKind.PrivateKeyword | SyntaxKind.ProtectedKeyword | SyntaxKind.PublicKeyword | SyntaxKind.ReadonlyKeyword | SyntaxKind.OverrideKeyword | SyntaxKind.StaticKeyword; + export type KeywordSyntaxKind = SyntaxKind.AbstractKeyword | SyntaxKind.AnyKeyword | SyntaxKind.AsKeyword | SyntaxKind.AssertsKeyword | SyntaxKind.AssertKeyword | SyntaxKind.AsyncKeyword | SyntaxKind.AwaitKeyword | SyntaxKind.BigIntKeyword | SyntaxKind.BooleanKeyword | SyntaxKind.BreakKeyword | SyntaxKind.CaseKeyword | SyntaxKind.CatchKeyword | SyntaxKind.ClassKeyword | SyntaxKind.ConstKeyword | SyntaxKind.ConstructorKeyword | SyntaxKind.ContinueKeyword | SyntaxKind.DebuggerKeyword | SyntaxKind.DeclareKeyword | SyntaxKind.DefaultKeyword | SyntaxKind.DeleteKeyword | SyntaxKind.DoKeyword | SyntaxKind.ElseKeyword | SyntaxKind.EnumKeyword | SyntaxKind.ExportKeyword | SyntaxKind.ExtendsKeyword | SyntaxKind.FalseKeyword | SyntaxKind.FinallyKeyword | SyntaxKind.ForKeyword | SyntaxKind.FromKeyword | SyntaxKind.FunctionKeyword | SyntaxKind.GetKeyword | SyntaxKind.GlobalKeyword | SyntaxKind.IfKeyword | SyntaxKind.ImplementsKeyword | SyntaxKind.ImportKeyword | SyntaxKind.InferKeyword | SyntaxKind.InKeyword | SyntaxKind.InstanceOfKeyword | SyntaxKind.InterfaceKeyword | SyntaxKind.IntrinsicKeyword | SyntaxKind.IsKeyword | SyntaxKind.KeyOfKeyword | SyntaxKind.LetKeyword | SyntaxKind.ModuleKeyword | SyntaxKind.NamespaceKeyword | SyntaxKind.NeverKeyword | SyntaxKind.NewKeyword | SyntaxKind.NullKeyword | SyntaxKind.NumberKeyword | SyntaxKind.ObjectKeyword | SyntaxKind.OfKeyword | SyntaxKind.PackageKeyword | SyntaxKind.PrivateKeyword | SyntaxKind.ProtectedKeyword | SyntaxKind.PublicKeyword | SyntaxKind.ReadonlyKeyword | SyntaxKind.OutKeyword | SyntaxKind.OverrideKeyword | SyntaxKind.RequireKeyword | SyntaxKind.ReturnKeyword | SyntaxKind.SetKeyword | SyntaxKind.StaticKeyword | SyntaxKind.StringKeyword | SyntaxKind.SuperKeyword | SyntaxKind.SwitchKeyword | SyntaxKind.SymbolKeyword | SyntaxKind.ThisKeyword | SyntaxKind.ThrowKeyword | SyntaxKind.TrueKeyword | SyntaxKind.TryKeyword | SyntaxKind.TypeKeyword | SyntaxKind.TypeOfKeyword | SyntaxKind.UndefinedKeyword | SyntaxKind.UniqueKeyword | SyntaxKind.UnknownKeyword | SyntaxKind.VarKeyword | SyntaxKind.VoidKeyword | SyntaxKind.WhileKeyword | SyntaxKind.WithKeyword | SyntaxKind.YieldKeyword; + export type ModifierSyntaxKind = SyntaxKind.AbstractKeyword | SyntaxKind.AsyncKeyword | SyntaxKind.ConstKeyword | SyntaxKind.DeclareKeyword | SyntaxKind.DefaultKeyword | SyntaxKind.ExportKeyword | SyntaxKind.InKeyword | SyntaxKind.PrivateKeyword | SyntaxKind.ProtectedKeyword | SyntaxKind.PublicKeyword | SyntaxKind.ReadonlyKeyword | SyntaxKind.OutKeyword | SyntaxKind.OverrideKeyword | SyntaxKind.StaticKeyword; export type KeywordTypeSyntaxKind = SyntaxKind.AnyKeyword | SyntaxKind.BigIntKeyword | SyntaxKind.BooleanKeyword | SyntaxKind.IntrinsicKeyword | SyntaxKind.NeverKeyword | SyntaxKind.NumberKeyword | SyntaxKind.ObjectKeyword | SyntaxKind.StringKeyword | SyntaxKind.SymbolKeyword | SyntaxKind.UndefinedKeyword | SyntaxKind.UnknownKeyword | SyntaxKind.VoidKeyword; export type TokenSyntaxKind = SyntaxKind.Unknown | SyntaxKind.EndOfFileToken | TriviaSyntaxKind | LiteralSyntaxKind | PseudoLiteralSyntaxKind | PunctuationSyntaxKind | SyntaxKind.Identifier | KeywordSyntaxKind; export type JsxTokenSyntaxKind = SyntaxKind.LessThanSlashToken | SyntaxKind.EndOfFileToken | SyntaxKind.ConflictMarkerTrivia | SyntaxKind.JsxText | SyntaxKind.JsxTextAllWhiteSpaces | SyntaxKind.OpenBraceToken | SyntaxKind.LessThanToken; @@ -550,13 +551,15 @@ declare namespace ts { HasComputedJSDocModifiers = 4096, Deprecated = 8192, Override = 16384, + In = 32768, + Out = 65536, HasComputedFlags = 536870912, AccessibilityModifier = 28, ParameterPropertyModifier = 16476, NonPublicAccessibilityModifier = 24, - TypeScriptModifier = 18654, + TypeScriptModifier = 116958, ExportDefault = 513, - All = 27647 + All = 125951 } export enum JsxFlags { None = 0, @@ -617,15 +620,17 @@ declare namespace ts { export type DeclareKeyword = ModifierToken; export type DefaultKeyword = ModifierToken; export type ExportKeyword = ModifierToken; + export type InKeyword = ModifierToken; export type PrivateKeyword = ModifierToken; export type ProtectedKeyword = ModifierToken; export type PublicKeyword = ModifierToken; export type ReadonlyKeyword = ModifierToken; + export type OutKeyword = ModifierToken; export type OverrideKeyword = ModifierToken; export type StaticKeyword = ModifierToken; /** @deprecated Use `ReadonlyKeyword` instead. */ export type ReadonlyToken = ReadonlyKeyword; - export type Modifier = AbstractKeyword | AsyncKeyword | ConstKeyword | DeclareKeyword | DefaultKeyword | ExportKeyword | PrivateKeyword | ProtectedKeyword | PublicKeyword | OverrideKeyword | ReadonlyKeyword | StaticKeyword; + export type Modifier = AbstractKeyword | AsyncKeyword | ConstKeyword | DeclareKeyword | DefaultKeyword | ExportKeyword | InKeyword | PrivateKeyword | ProtectedKeyword | PublicKeyword | OutKeyword | OverrideKeyword | ReadonlyKeyword | StaticKeyword; export type AccessibilityModifier = PublicKeyword | PrivateKeyword | ProtectedKeyword; export type ParameterPropertyModifier = AccessibilityModifier | ReadonlyKeyword; export type ClassMemberModifier = AccessibilityModifier | ReadonlyKeyword | StaticKeyword; @@ -2670,14 +2675,13 @@ declare namespace ts { ObjectLiteralPatternWithComputedProperties = 512, ReverseMapped = 1024, JsxAttributes = 2048, - MarkerType = 4096, - JSLiteral = 8192, - FreshLiteral = 16384, - ArrayLiteral = 32768, + JSLiteral = 4096, + FreshLiteral = 8192, + ArrayLiteral = 16384, ClassOrInterface = 3, - ContainsSpread = 4194304, - ObjectRestType = 8388608, - InstantiationExpressionType = 16777216, + ContainsSpread = 2097152, + ObjectRestType = 4194304, + InstantiationExpressionType = 8388608, } export interface ObjectType extends Type { objectFlags: ObjectFlags; @@ -3392,7 +3396,11 @@ declare namespace ts { updateQualifiedName(node: QualifiedName, left: EntityName, right: Identifier): QualifiedName; createComputedPropertyName(expression: Expression): ComputedPropertyName; updateComputedPropertyName(node: ComputedPropertyName, expression: Expression): ComputedPropertyName; + createTypeParameterDeclaration(modifiers: readonly Modifier[] | undefined, name: string | Identifier, constraint?: TypeNode, defaultType?: TypeNode): TypeParameterDeclaration; + /** @deprecated */ createTypeParameterDeclaration(name: string | Identifier, constraint?: TypeNode, defaultType?: TypeNode): TypeParameterDeclaration; + updateTypeParameterDeclaration(node: TypeParameterDeclaration, modifiers: readonly Modifier[] | undefined, name: Identifier, constraint: TypeNode | undefined, defaultType: TypeNode | undefined): TypeParameterDeclaration; + /** @deprecated */ updateTypeParameterDeclaration(node: TypeParameterDeclaration, name: Identifier, constraint: TypeNode | undefined, defaultType: TypeNode | undefined): TypeParameterDeclaration; createParameterDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, dotDotDotToken: DotDotDotToken | undefined, name: string | BindingName, questionToken?: QuestionToken, type?: TypeNode, initializer?: Expression): ParameterDeclaration; updateParameterDeclaration(node: ParameterDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, dotDotDotToken: DotDotDotToken | undefined, name: string | BindingName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): ParameterDeclaration; @@ -10787,9 +10795,15 @@ declare namespace ts { /** @deprecated Use `factory.updateComputedPropertyName` or the factory supplied by your transformation context instead. */ const updateComputedPropertyName: (node: ComputedPropertyName, expression: Expression) => ComputedPropertyName; /** @deprecated Use `factory.createTypeParameterDeclaration` or the factory supplied by your transformation context instead. */ - const createTypeParameterDeclaration: (name: string | Identifier, constraint?: TypeNode | undefined, defaultType?: TypeNode | undefined) => TypeParameterDeclaration; + const createTypeParameterDeclaration: { + (modifiers: readonly Modifier[] | undefined, name: string | Identifier, constraint?: TypeNode | undefined, defaultType?: TypeNode | undefined): TypeParameterDeclaration; + (name: string | Identifier, constraint?: TypeNode | undefined, defaultType?: TypeNode | undefined): TypeParameterDeclaration; + }; /** @deprecated Use `factory.updateTypeParameterDeclaration` or the factory supplied by your transformation context instead. */ - const updateTypeParameterDeclaration: (node: TypeParameterDeclaration, name: Identifier, constraint: TypeNode | undefined, defaultType: TypeNode | undefined) => TypeParameterDeclaration; + const updateTypeParameterDeclaration: { + (node: TypeParameterDeclaration, modifiers: readonly Modifier[] | undefined, name: Identifier, constraint: TypeNode | undefined, defaultType: TypeNode | undefined): TypeParameterDeclaration; + (node: TypeParameterDeclaration, name: Identifier, constraint: TypeNode | undefined, defaultType: TypeNode | undefined): TypeParameterDeclaration; + }; /** @deprecated Use `factory.createParameterDeclaration` or the factory supplied by your transformation context instead. */ const createParameter: (decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, dotDotDotToken: DotDotDotToken | undefined, name: string | BindingName, questionToken?: QuestionToken | undefined, type?: TypeNode | undefined, initializer?: Expression | undefined) => ParameterDeclaration; /** @deprecated Use `factory.updateParameterDeclaration` or the factory supplied by your transformation context instead. */ diff --git a/tests/baselines/reference/api/typescript.d.ts b/tests/baselines/reference/api/typescript.d.ts index e78e7d779b8..9e1c635ac74 100644 --- a/tests/baselines/reference/api/typescript.d.ts +++ b/tests/baselines/reference/api/typescript.d.ts @@ -249,218 +249,219 @@ declare namespace ts { ModuleKeyword = 141, NamespaceKeyword = 142, NeverKeyword = 143, - ReadonlyKeyword = 144, - RequireKeyword = 145, - NumberKeyword = 146, - ObjectKeyword = 147, - SetKeyword = 148, - StringKeyword = 149, - SymbolKeyword = 150, - TypeKeyword = 151, - UndefinedKeyword = 152, - UniqueKeyword = 153, - UnknownKeyword = 154, - FromKeyword = 155, - GlobalKeyword = 156, - BigIntKeyword = 157, - OverrideKeyword = 158, - OfKeyword = 159, - QualifiedName = 160, - ComputedPropertyName = 161, - TypeParameter = 162, - Parameter = 163, - Decorator = 164, - PropertySignature = 165, - PropertyDeclaration = 166, - MethodSignature = 167, - MethodDeclaration = 168, - ClassStaticBlockDeclaration = 169, - Constructor = 170, - GetAccessor = 171, - SetAccessor = 172, - CallSignature = 173, - ConstructSignature = 174, - IndexSignature = 175, - TypePredicate = 176, - TypeReference = 177, - FunctionType = 178, - ConstructorType = 179, - TypeQuery = 180, - TypeLiteral = 181, - ArrayType = 182, - TupleType = 183, - OptionalType = 184, - RestType = 185, - UnionType = 186, - IntersectionType = 187, - ConditionalType = 188, - InferType = 189, - ParenthesizedType = 190, - ThisType = 191, - TypeOperator = 192, - IndexedAccessType = 193, - MappedType = 194, - LiteralType = 195, - NamedTupleMember = 196, - TemplateLiteralType = 197, - TemplateLiteralTypeSpan = 198, - ImportType = 199, - ObjectBindingPattern = 200, - ArrayBindingPattern = 201, - BindingElement = 202, - ArrayLiteralExpression = 203, - ObjectLiteralExpression = 204, - PropertyAccessExpression = 205, - ElementAccessExpression = 206, - CallExpression = 207, - NewExpression = 208, - TaggedTemplateExpression = 209, - TypeAssertionExpression = 210, - ParenthesizedExpression = 211, - FunctionExpression = 212, - ArrowFunction = 213, - DeleteExpression = 214, - TypeOfExpression = 215, - VoidExpression = 216, - AwaitExpression = 217, - PrefixUnaryExpression = 218, - PostfixUnaryExpression = 219, - BinaryExpression = 220, - ConditionalExpression = 221, - TemplateExpression = 222, - YieldExpression = 223, - SpreadElement = 224, - ClassExpression = 225, - OmittedExpression = 226, - ExpressionWithTypeArguments = 227, - AsExpression = 228, - NonNullExpression = 229, - MetaProperty = 230, - SyntheticExpression = 231, - TemplateSpan = 232, - SemicolonClassElement = 233, - Block = 234, - EmptyStatement = 235, - VariableStatement = 236, - ExpressionStatement = 237, - IfStatement = 238, - DoStatement = 239, - WhileStatement = 240, - ForStatement = 241, - ForInStatement = 242, - ForOfStatement = 243, - ContinueStatement = 244, - BreakStatement = 245, - ReturnStatement = 246, - WithStatement = 247, - SwitchStatement = 248, - LabeledStatement = 249, - ThrowStatement = 250, - TryStatement = 251, - DebuggerStatement = 252, - VariableDeclaration = 253, - VariableDeclarationList = 254, - FunctionDeclaration = 255, - ClassDeclaration = 256, - InterfaceDeclaration = 257, - TypeAliasDeclaration = 258, - EnumDeclaration = 259, - ModuleDeclaration = 260, - ModuleBlock = 261, - CaseBlock = 262, - NamespaceExportDeclaration = 263, - ImportEqualsDeclaration = 264, - ImportDeclaration = 265, - ImportClause = 266, - NamespaceImport = 267, - NamedImports = 268, - ImportSpecifier = 269, - ExportAssignment = 270, - ExportDeclaration = 271, - NamedExports = 272, - NamespaceExport = 273, - ExportSpecifier = 274, - MissingDeclaration = 275, - ExternalModuleReference = 276, - JsxElement = 277, - JsxSelfClosingElement = 278, - JsxOpeningElement = 279, - JsxClosingElement = 280, - JsxFragment = 281, - JsxOpeningFragment = 282, - JsxClosingFragment = 283, - JsxAttribute = 284, - JsxAttributes = 285, - JsxSpreadAttribute = 286, - JsxExpression = 287, - CaseClause = 288, - DefaultClause = 289, - HeritageClause = 290, - CatchClause = 291, - AssertClause = 292, - AssertEntry = 293, - ImportTypeAssertionContainer = 294, - PropertyAssignment = 295, - ShorthandPropertyAssignment = 296, - SpreadAssignment = 297, - EnumMember = 298, - UnparsedPrologue = 299, - UnparsedPrepend = 300, - UnparsedText = 301, - UnparsedInternalText = 302, - UnparsedSyntheticReference = 303, - SourceFile = 304, - Bundle = 305, - UnparsedSource = 306, - InputFiles = 307, - JSDocTypeExpression = 308, - JSDocNameReference = 309, - JSDocMemberName = 310, - JSDocAllType = 311, - JSDocUnknownType = 312, - JSDocNullableType = 313, - JSDocNonNullableType = 314, - JSDocOptionalType = 315, - JSDocFunctionType = 316, - JSDocVariadicType = 317, - JSDocNamepathType = 318, + OutKeyword = 144, + ReadonlyKeyword = 145, + RequireKeyword = 146, + NumberKeyword = 147, + ObjectKeyword = 148, + SetKeyword = 149, + StringKeyword = 150, + SymbolKeyword = 151, + TypeKeyword = 152, + UndefinedKeyword = 153, + UniqueKeyword = 154, + UnknownKeyword = 155, + FromKeyword = 156, + GlobalKeyword = 157, + BigIntKeyword = 158, + OverrideKeyword = 159, + OfKeyword = 160, + QualifiedName = 161, + ComputedPropertyName = 162, + TypeParameter = 163, + Parameter = 164, + Decorator = 165, + PropertySignature = 166, + PropertyDeclaration = 167, + MethodSignature = 168, + MethodDeclaration = 169, + ClassStaticBlockDeclaration = 170, + Constructor = 171, + GetAccessor = 172, + SetAccessor = 173, + CallSignature = 174, + ConstructSignature = 175, + IndexSignature = 176, + TypePredicate = 177, + TypeReference = 178, + FunctionType = 179, + ConstructorType = 180, + TypeQuery = 181, + TypeLiteral = 182, + ArrayType = 183, + TupleType = 184, + OptionalType = 185, + RestType = 186, + UnionType = 187, + IntersectionType = 188, + ConditionalType = 189, + InferType = 190, + ParenthesizedType = 191, + ThisType = 192, + TypeOperator = 193, + IndexedAccessType = 194, + MappedType = 195, + LiteralType = 196, + NamedTupleMember = 197, + TemplateLiteralType = 198, + TemplateLiteralTypeSpan = 199, + ImportType = 200, + ObjectBindingPattern = 201, + ArrayBindingPattern = 202, + BindingElement = 203, + ArrayLiteralExpression = 204, + ObjectLiteralExpression = 205, + PropertyAccessExpression = 206, + ElementAccessExpression = 207, + CallExpression = 208, + NewExpression = 209, + TaggedTemplateExpression = 210, + TypeAssertionExpression = 211, + ParenthesizedExpression = 212, + FunctionExpression = 213, + ArrowFunction = 214, + DeleteExpression = 215, + TypeOfExpression = 216, + VoidExpression = 217, + AwaitExpression = 218, + PrefixUnaryExpression = 219, + PostfixUnaryExpression = 220, + BinaryExpression = 221, + ConditionalExpression = 222, + TemplateExpression = 223, + YieldExpression = 224, + SpreadElement = 225, + ClassExpression = 226, + OmittedExpression = 227, + ExpressionWithTypeArguments = 228, + AsExpression = 229, + NonNullExpression = 230, + MetaProperty = 231, + SyntheticExpression = 232, + TemplateSpan = 233, + SemicolonClassElement = 234, + Block = 235, + EmptyStatement = 236, + VariableStatement = 237, + ExpressionStatement = 238, + IfStatement = 239, + DoStatement = 240, + WhileStatement = 241, + ForStatement = 242, + ForInStatement = 243, + ForOfStatement = 244, + ContinueStatement = 245, + BreakStatement = 246, + ReturnStatement = 247, + WithStatement = 248, + SwitchStatement = 249, + LabeledStatement = 250, + ThrowStatement = 251, + TryStatement = 252, + DebuggerStatement = 253, + VariableDeclaration = 254, + VariableDeclarationList = 255, + FunctionDeclaration = 256, + ClassDeclaration = 257, + InterfaceDeclaration = 258, + TypeAliasDeclaration = 259, + EnumDeclaration = 260, + ModuleDeclaration = 261, + ModuleBlock = 262, + CaseBlock = 263, + NamespaceExportDeclaration = 264, + ImportEqualsDeclaration = 265, + ImportDeclaration = 266, + ImportClause = 267, + NamespaceImport = 268, + NamedImports = 269, + ImportSpecifier = 270, + ExportAssignment = 271, + ExportDeclaration = 272, + NamedExports = 273, + NamespaceExport = 274, + ExportSpecifier = 275, + MissingDeclaration = 276, + ExternalModuleReference = 277, + JsxElement = 278, + JsxSelfClosingElement = 279, + JsxOpeningElement = 280, + JsxClosingElement = 281, + JsxFragment = 282, + JsxOpeningFragment = 283, + JsxClosingFragment = 284, + JsxAttribute = 285, + JsxAttributes = 286, + JsxSpreadAttribute = 287, + JsxExpression = 288, + CaseClause = 289, + DefaultClause = 290, + HeritageClause = 291, + CatchClause = 292, + AssertClause = 293, + AssertEntry = 294, + ImportTypeAssertionContainer = 295, + PropertyAssignment = 296, + ShorthandPropertyAssignment = 297, + SpreadAssignment = 298, + EnumMember = 299, + UnparsedPrologue = 300, + UnparsedPrepend = 301, + UnparsedText = 302, + UnparsedInternalText = 303, + UnparsedSyntheticReference = 304, + SourceFile = 305, + Bundle = 306, + UnparsedSource = 307, + InputFiles = 308, + JSDocTypeExpression = 309, + JSDocNameReference = 310, + JSDocMemberName = 311, + JSDocAllType = 312, + JSDocUnknownType = 313, + JSDocNullableType = 314, + JSDocNonNullableType = 315, + JSDocOptionalType = 316, + JSDocFunctionType = 317, + JSDocVariadicType = 318, + JSDocNamepathType = 319, /** @deprecated Use SyntaxKind.JSDoc */ - JSDocComment = 319, - JSDocText = 320, - JSDocTypeLiteral = 321, - JSDocSignature = 322, - JSDocLink = 323, - JSDocLinkCode = 324, - JSDocLinkPlain = 325, - JSDocTag = 326, - JSDocAugmentsTag = 327, - JSDocImplementsTag = 328, - JSDocAuthorTag = 329, - JSDocDeprecatedTag = 330, - JSDocClassTag = 331, - JSDocPublicTag = 332, - JSDocPrivateTag = 333, - JSDocProtectedTag = 334, - JSDocReadonlyTag = 335, - JSDocOverrideTag = 336, - JSDocCallbackTag = 337, - JSDocEnumTag = 338, - JSDocParameterTag = 339, - JSDocReturnTag = 340, - JSDocThisTag = 341, - JSDocTypeTag = 342, - JSDocTemplateTag = 343, - JSDocTypedefTag = 344, - JSDocSeeTag = 345, - JSDocPropertyTag = 346, - SyntaxList = 347, - NotEmittedStatement = 348, - PartiallyEmittedExpression = 349, - CommaListExpression = 350, - MergeDeclarationMarker = 351, - EndOfDeclarationMarker = 352, - SyntheticReferenceExpression = 353, - Count = 354, + JSDocComment = 320, + JSDocText = 321, + JSDocTypeLiteral = 322, + JSDocSignature = 323, + JSDocLink = 324, + JSDocLinkCode = 325, + JSDocLinkPlain = 326, + JSDocTag = 327, + JSDocAugmentsTag = 328, + JSDocImplementsTag = 329, + JSDocAuthorTag = 330, + JSDocDeprecatedTag = 331, + JSDocClassTag = 332, + JSDocPublicTag = 333, + JSDocPrivateTag = 334, + JSDocProtectedTag = 335, + JSDocReadonlyTag = 336, + JSDocOverrideTag = 337, + JSDocCallbackTag = 338, + JSDocEnumTag = 339, + JSDocParameterTag = 340, + JSDocReturnTag = 341, + JSDocThisTag = 342, + JSDocTypeTag = 343, + JSDocTemplateTag = 344, + JSDocTypedefTag = 345, + JSDocSeeTag = 346, + JSDocPropertyTag = 347, + SyntaxList = 348, + NotEmittedStatement = 349, + PartiallyEmittedExpression = 350, + CommaListExpression = 351, + MergeDeclarationMarker = 352, + EndOfDeclarationMarker = 353, + SyntheticReferenceExpression = 354, + Count = 355, FirstAssignment = 63, LastAssignment = 78, FirstCompoundAssignment = 64, @@ -468,15 +469,15 @@ declare namespace ts { FirstReservedWord = 81, LastReservedWord = 116, FirstKeyword = 81, - LastKeyword = 159, + LastKeyword = 160, FirstFutureReservedWord = 117, LastFutureReservedWord = 125, - FirstTypeNode = 176, - LastTypeNode = 199, + FirstTypeNode = 177, + LastTypeNode = 200, FirstPunctuation = 18, LastPunctuation = 78, FirstToken = 0, - LastToken = 159, + LastToken = 160, FirstTriviaToken = 2, LastTriviaToken = 7, FirstLiteralToken = 8, @@ -485,21 +486,21 @@ declare namespace ts { LastTemplateToken = 17, FirstBinaryOperator = 29, LastBinaryOperator = 78, - FirstStatement = 236, - LastStatement = 252, - FirstNode = 160, - FirstJSDocNode = 308, - LastJSDocNode = 346, - FirstJSDocTagNode = 326, - LastJSDocTagNode = 346, - JSDoc = 319 + FirstStatement = 237, + LastStatement = 253, + FirstNode = 161, + FirstJSDocNode = 309, + LastJSDocNode = 347, + FirstJSDocTagNode = 327, + LastJSDocTagNode = 347, + JSDoc = 320 } export type TriviaSyntaxKind = SyntaxKind.SingleLineCommentTrivia | SyntaxKind.MultiLineCommentTrivia | SyntaxKind.NewLineTrivia | SyntaxKind.WhitespaceTrivia | SyntaxKind.ShebangTrivia | SyntaxKind.ConflictMarkerTrivia; export type LiteralSyntaxKind = SyntaxKind.NumericLiteral | SyntaxKind.BigIntLiteral | SyntaxKind.StringLiteral | SyntaxKind.JsxText | SyntaxKind.JsxTextAllWhiteSpaces | SyntaxKind.RegularExpressionLiteral | SyntaxKind.NoSubstitutionTemplateLiteral; export type PseudoLiteralSyntaxKind = SyntaxKind.TemplateHead | SyntaxKind.TemplateMiddle | SyntaxKind.TemplateTail; export type PunctuationSyntaxKind = SyntaxKind.OpenBraceToken | SyntaxKind.CloseBraceToken | SyntaxKind.OpenParenToken | SyntaxKind.CloseParenToken | SyntaxKind.OpenBracketToken | SyntaxKind.CloseBracketToken | SyntaxKind.DotToken | SyntaxKind.DotDotDotToken | SyntaxKind.SemicolonToken | SyntaxKind.CommaToken | SyntaxKind.QuestionDotToken | SyntaxKind.LessThanToken | SyntaxKind.LessThanSlashToken | SyntaxKind.GreaterThanToken | SyntaxKind.LessThanEqualsToken | SyntaxKind.GreaterThanEqualsToken | SyntaxKind.EqualsEqualsToken | SyntaxKind.ExclamationEqualsToken | SyntaxKind.EqualsEqualsEqualsToken | SyntaxKind.ExclamationEqualsEqualsToken | SyntaxKind.EqualsGreaterThanToken | SyntaxKind.PlusToken | SyntaxKind.MinusToken | SyntaxKind.AsteriskToken | SyntaxKind.AsteriskAsteriskToken | SyntaxKind.SlashToken | SyntaxKind.PercentToken | SyntaxKind.PlusPlusToken | SyntaxKind.MinusMinusToken | SyntaxKind.LessThanLessThanToken | SyntaxKind.GreaterThanGreaterThanToken | SyntaxKind.GreaterThanGreaterThanGreaterThanToken | SyntaxKind.AmpersandToken | SyntaxKind.BarToken | SyntaxKind.CaretToken | SyntaxKind.ExclamationToken | SyntaxKind.TildeToken | SyntaxKind.AmpersandAmpersandToken | SyntaxKind.BarBarToken | SyntaxKind.QuestionQuestionToken | SyntaxKind.QuestionToken | SyntaxKind.ColonToken | SyntaxKind.AtToken | SyntaxKind.BacktickToken | SyntaxKind.HashToken | SyntaxKind.EqualsToken | SyntaxKind.PlusEqualsToken | SyntaxKind.MinusEqualsToken | SyntaxKind.AsteriskEqualsToken | SyntaxKind.AsteriskAsteriskEqualsToken | SyntaxKind.SlashEqualsToken | SyntaxKind.PercentEqualsToken | SyntaxKind.LessThanLessThanEqualsToken | SyntaxKind.GreaterThanGreaterThanEqualsToken | SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken | SyntaxKind.AmpersandEqualsToken | SyntaxKind.BarEqualsToken | SyntaxKind.CaretEqualsToken; - export type KeywordSyntaxKind = SyntaxKind.AbstractKeyword | SyntaxKind.AnyKeyword | SyntaxKind.AsKeyword | SyntaxKind.AssertsKeyword | SyntaxKind.AssertKeyword | SyntaxKind.AsyncKeyword | SyntaxKind.AwaitKeyword | SyntaxKind.BigIntKeyword | SyntaxKind.BooleanKeyword | SyntaxKind.BreakKeyword | SyntaxKind.CaseKeyword | SyntaxKind.CatchKeyword | SyntaxKind.ClassKeyword | SyntaxKind.ConstKeyword | SyntaxKind.ConstructorKeyword | SyntaxKind.ContinueKeyword | SyntaxKind.DebuggerKeyword | SyntaxKind.DeclareKeyword | SyntaxKind.DefaultKeyword | SyntaxKind.DeleteKeyword | SyntaxKind.DoKeyword | SyntaxKind.ElseKeyword | SyntaxKind.EnumKeyword | SyntaxKind.ExportKeyword | SyntaxKind.ExtendsKeyword | SyntaxKind.FalseKeyword | SyntaxKind.FinallyKeyword | SyntaxKind.ForKeyword | SyntaxKind.FromKeyword | SyntaxKind.FunctionKeyword | SyntaxKind.GetKeyword | SyntaxKind.GlobalKeyword | SyntaxKind.IfKeyword | SyntaxKind.ImplementsKeyword | SyntaxKind.ImportKeyword | SyntaxKind.InferKeyword | SyntaxKind.InKeyword | SyntaxKind.InstanceOfKeyword | SyntaxKind.InterfaceKeyword | SyntaxKind.IntrinsicKeyword | SyntaxKind.IsKeyword | SyntaxKind.KeyOfKeyword | SyntaxKind.LetKeyword | SyntaxKind.ModuleKeyword | SyntaxKind.NamespaceKeyword | SyntaxKind.NeverKeyword | SyntaxKind.NewKeyword | SyntaxKind.NullKeyword | SyntaxKind.NumberKeyword | SyntaxKind.ObjectKeyword | SyntaxKind.OfKeyword | SyntaxKind.PackageKeyword | SyntaxKind.PrivateKeyword | SyntaxKind.ProtectedKeyword | SyntaxKind.PublicKeyword | SyntaxKind.ReadonlyKeyword | SyntaxKind.OverrideKeyword | SyntaxKind.RequireKeyword | SyntaxKind.ReturnKeyword | SyntaxKind.SetKeyword | SyntaxKind.StaticKeyword | SyntaxKind.StringKeyword | SyntaxKind.SuperKeyword | SyntaxKind.SwitchKeyword | SyntaxKind.SymbolKeyword | SyntaxKind.ThisKeyword | SyntaxKind.ThrowKeyword | SyntaxKind.TrueKeyword | SyntaxKind.TryKeyword | SyntaxKind.TypeKeyword | SyntaxKind.TypeOfKeyword | SyntaxKind.UndefinedKeyword | SyntaxKind.UniqueKeyword | SyntaxKind.UnknownKeyword | SyntaxKind.VarKeyword | SyntaxKind.VoidKeyword | SyntaxKind.WhileKeyword | SyntaxKind.WithKeyword | SyntaxKind.YieldKeyword; - export type ModifierSyntaxKind = SyntaxKind.AbstractKeyword | SyntaxKind.AsyncKeyword | SyntaxKind.ConstKeyword | SyntaxKind.DeclareKeyword | SyntaxKind.DefaultKeyword | SyntaxKind.ExportKeyword | SyntaxKind.PrivateKeyword | SyntaxKind.ProtectedKeyword | SyntaxKind.PublicKeyword | SyntaxKind.ReadonlyKeyword | SyntaxKind.OverrideKeyword | SyntaxKind.StaticKeyword; + export type KeywordSyntaxKind = SyntaxKind.AbstractKeyword | SyntaxKind.AnyKeyword | SyntaxKind.AsKeyword | SyntaxKind.AssertsKeyword | SyntaxKind.AssertKeyword | SyntaxKind.AsyncKeyword | SyntaxKind.AwaitKeyword | SyntaxKind.BigIntKeyword | SyntaxKind.BooleanKeyword | SyntaxKind.BreakKeyword | SyntaxKind.CaseKeyword | SyntaxKind.CatchKeyword | SyntaxKind.ClassKeyword | SyntaxKind.ConstKeyword | SyntaxKind.ConstructorKeyword | SyntaxKind.ContinueKeyword | SyntaxKind.DebuggerKeyword | SyntaxKind.DeclareKeyword | SyntaxKind.DefaultKeyword | SyntaxKind.DeleteKeyword | SyntaxKind.DoKeyword | SyntaxKind.ElseKeyword | SyntaxKind.EnumKeyword | SyntaxKind.ExportKeyword | SyntaxKind.ExtendsKeyword | SyntaxKind.FalseKeyword | SyntaxKind.FinallyKeyword | SyntaxKind.ForKeyword | SyntaxKind.FromKeyword | SyntaxKind.FunctionKeyword | SyntaxKind.GetKeyword | SyntaxKind.GlobalKeyword | SyntaxKind.IfKeyword | SyntaxKind.ImplementsKeyword | SyntaxKind.ImportKeyword | SyntaxKind.InferKeyword | SyntaxKind.InKeyword | SyntaxKind.InstanceOfKeyword | SyntaxKind.InterfaceKeyword | SyntaxKind.IntrinsicKeyword | SyntaxKind.IsKeyword | SyntaxKind.KeyOfKeyword | SyntaxKind.LetKeyword | SyntaxKind.ModuleKeyword | SyntaxKind.NamespaceKeyword | SyntaxKind.NeverKeyword | SyntaxKind.NewKeyword | SyntaxKind.NullKeyword | SyntaxKind.NumberKeyword | SyntaxKind.ObjectKeyword | SyntaxKind.OfKeyword | SyntaxKind.PackageKeyword | SyntaxKind.PrivateKeyword | SyntaxKind.ProtectedKeyword | SyntaxKind.PublicKeyword | SyntaxKind.ReadonlyKeyword | SyntaxKind.OutKeyword | SyntaxKind.OverrideKeyword | SyntaxKind.RequireKeyword | SyntaxKind.ReturnKeyword | SyntaxKind.SetKeyword | SyntaxKind.StaticKeyword | SyntaxKind.StringKeyword | SyntaxKind.SuperKeyword | SyntaxKind.SwitchKeyword | SyntaxKind.SymbolKeyword | SyntaxKind.ThisKeyword | SyntaxKind.ThrowKeyword | SyntaxKind.TrueKeyword | SyntaxKind.TryKeyword | SyntaxKind.TypeKeyword | SyntaxKind.TypeOfKeyword | SyntaxKind.UndefinedKeyword | SyntaxKind.UniqueKeyword | SyntaxKind.UnknownKeyword | SyntaxKind.VarKeyword | SyntaxKind.VoidKeyword | SyntaxKind.WhileKeyword | SyntaxKind.WithKeyword | SyntaxKind.YieldKeyword; + export type ModifierSyntaxKind = SyntaxKind.AbstractKeyword | SyntaxKind.AsyncKeyword | SyntaxKind.ConstKeyword | SyntaxKind.DeclareKeyword | SyntaxKind.DefaultKeyword | SyntaxKind.ExportKeyword | SyntaxKind.InKeyword | SyntaxKind.PrivateKeyword | SyntaxKind.ProtectedKeyword | SyntaxKind.PublicKeyword | SyntaxKind.ReadonlyKeyword | SyntaxKind.OutKeyword | SyntaxKind.OverrideKeyword | SyntaxKind.StaticKeyword; export type KeywordTypeSyntaxKind = SyntaxKind.AnyKeyword | SyntaxKind.BigIntKeyword | SyntaxKind.BooleanKeyword | SyntaxKind.IntrinsicKeyword | SyntaxKind.NeverKeyword | SyntaxKind.NumberKeyword | SyntaxKind.ObjectKeyword | SyntaxKind.StringKeyword | SyntaxKind.SymbolKeyword | SyntaxKind.UndefinedKeyword | SyntaxKind.UnknownKeyword | SyntaxKind.VoidKeyword; export type TokenSyntaxKind = SyntaxKind.Unknown | SyntaxKind.EndOfFileToken | TriviaSyntaxKind | LiteralSyntaxKind | PseudoLiteralSyntaxKind | PunctuationSyntaxKind | SyntaxKind.Identifier | KeywordSyntaxKind; export type JsxTokenSyntaxKind = SyntaxKind.LessThanSlashToken | SyntaxKind.EndOfFileToken | SyntaxKind.ConflictMarkerTrivia | SyntaxKind.JsxText | SyntaxKind.JsxTextAllWhiteSpaces | SyntaxKind.OpenBraceToken | SyntaxKind.LessThanToken; @@ -550,13 +551,15 @@ declare namespace ts { HasComputedJSDocModifiers = 4096, Deprecated = 8192, Override = 16384, + In = 32768, + Out = 65536, HasComputedFlags = 536870912, AccessibilityModifier = 28, ParameterPropertyModifier = 16476, NonPublicAccessibilityModifier = 24, - TypeScriptModifier = 18654, + TypeScriptModifier = 116958, ExportDefault = 513, - All = 27647 + All = 125951 } export enum JsxFlags { None = 0, @@ -617,15 +620,17 @@ declare namespace ts { export type DeclareKeyword = ModifierToken; export type DefaultKeyword = ModifierToken; export type ExportKeyword = ModifierToken; + export type InKeyword = ModifierToken; export type PrivateKeyword = ModifierToken; export type ProtectedKeyword = ModifierToken; export type PublicKeyword = ModifierToken; export type ReadonlyKeyword = ModifierToken; + export type OutKeyword = ModifierToken; export type OverrideKeyword = ModifierToken; export type StaticKeyword = ModifierToken; /** @deprecated Use `ReadonlyKeyword` instead. */ export type ReadonlyToken = ReadonlyKeyword; - export type Modifier = AbstractKeyword | AsyncKeyword | ConstKeyword | DeclareKeyword | DefaultKeyword | ExportKeyword | PrivateKeyword | ProtectedKeyword | PublicKeyword | OverrideKeyword | ReadonlyKeyword | StaticKeyword; + export type Modifier = AbstractKeyword | AsyncKeyword | ConstKeyword | DeclareKeyword | DefaultKeyword | ExportKeyword | InKeyword | PrivateKeyword | ProtectedKeyword | PublicKeyword | OutKeyword | OverrideKeyword | ReadonlyKeyword | StaticKeyword; export type AccessibilityModifier = PublicKeyword | PrivateKeyword | ProtectedKeyword; export type ParameterPropertyModifier = AccessibilityModifier | ReadonlyKeyword; export type ClassMemberModifier = AccessibilityModifier | ReadonlyKeyword | StaticKeyword; @@ -2670,14 +2675,13 @@ declare namespace ts { ObjectLiteralPatternWithComputedProperties = 512, ReverseMapped = 1024, JsxAttributes = 2048, - MarkerType = 4096, - JSLiteral = 8192, - FreshLiteral = 16384, - ArrayLiteral = 32768, + JSLiteral = 4096, + FreshLiteral = 8192, + ArrayLiteral = 16384, ClassOrInterface = 3, - ContainsSpread = 4194304, - ObjectRestType = 8388608, - InstantiationExpressionType = 16777216, + ContainsSpread = 2097152, + ObjectRestType = 4194304, + InstantiationExpressionType = 8388608, } export interface ObjectType extends Type { objectFlags: ObjectFlags; @@ -3392,7 +3396,11 @@ declare namespace ts { updateQualifiedName(node: QualifiedName, left: EntityName, right: Identifier): QualifiedName; createComputedPropertyName(expression: Expression): ComputedPropertyName; updateComputedPropertyName(node: ComputedPropertyName, expression: Expression): ComputedPropertyName; + createTypeParameterDeclaration(modifiers: readonly Modifier[] | undefined, name: string | Identifier, constraint?: TypeNode, defaultType?: TypeNode): TypeParameterDeclaration; + /** @deprecated */ createTypeParameterDeclaration(name: string | Identifier, constraint?: TypeNode, defaultType?: TypeNode): TypeParameterDeclaration; + updateTypeParameterDeclaration(node: TypeParameterDeclaration, modifiers: readonly Modifier[] | undefined, name: Identifier, constraint: TypeNode | undefined, defaultType: TypeNode | undefined): TypeParameterDeclaration; + /** @deprecated */ updateTypeParameterDeclaration(node: TypeParameterDeclaration, name: Identifier, constraint: TypeNode | undefined, defaultType: TypeNode | undefined): TypeParameterDeclaration; createParameterDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, dotDotDotToken: DotDotDotToken | undefined, name: string | BindingName, questionToken?: QuestionToken, type?: TypeNode, initializer?: Expression): ParameterDeclaration; updateParameterDeclaration(node: ParameterDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, dotDotDotToken: DotDotDotToken | undefined, name: string | BindingName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): ParameterDeclaration; @@ -6940,9 +6948,15 @@ declare namespace ts { /** @deprecated Use `factory.updateComputedPropertyName` or the factory supplied by your transformation context instead. */ const updateComputedPropertyName: (node: ComputedPropertyName, expression: Expression) => ComputedPropertyName; /** @deprecated Use `factory.createTypeParameterDeclaration` or the factory supplied by your transformation context instead. */ - const createTypeParameterDeclaration: (name: string | Identifier, constraint?: TypeNode | undefined, defaultType?: TypeNode | undefined) => TypeParameterDeclaration; + const createTypeParameterDeclaration: { + (modifiers: readonly Modifier[] | undefined, name: string | Identifier, constraint?: TypeNode | undefined, defaultType?: TypeNode | undefined): TypeParameterDeclaration; + (name: string | Identifier, constraint?: TypeNode | undefined, defaultType?: TypeNode | undefined): TypeParameterDeclaration; + }; /** @deprecated Use `factory.updateTypeParameterDeclaration` or the factory supplied by your transformation context instead. */ - const updateTypeParameterDeclaration: (node: TypeParameterDeclaration, name: Identifier, constraint: TypeNode | undefined, defaultType: TypeNode | undefined) => TypeParameterDeclaration; + const updateTypeParameterDeclaration: { + (node: TypeParameterDeclaration, modifiers: readonly Modifier[] | undefined, name: Identifier, constraint: TypeNode | undefined, defaultType: TypeNode | undefined): TypeParameterDeclaration; + (node: TypeParameterDeclaration, name: Identifier, constraint: TypeNode | undefined, defaultType: TypeNode | undefined): TypeParameterDeclaration; + }; /** @deprecated Use `factory.createParameterDeclaration` or the factory supplied by your transformation context instead. */ const createParameter: (decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, dotDotDotToken: DotDotDotToken | undefined, name: string | BindingName, questionToken?: QuestionToken | undefined, type?: TypeNode | undefined, initializer?: Expression | undefined) => ParameterDeclaration; /** @deprecated Use `factory.updateParameterDeclaration` or the factory supplied by your transformation context instead. */ diff --git a/tests/baselines/reference/circularAccessorAnnotations.errors.txt b/tests/baselines/reference/circularAccessorAnnotations.errors.txt new file mode 100644 index 00000000000..890726fcaf6 --- /dev/null +++ b/tests/baselines/reference/circularAccessorAnnotations.errors.txt @@ -0,0 +1,41 @@ +tests/cases/compiler/circularAccessorAnnotations.ts(2,9): error TS2502: 'foo' is referenced directly or indirectly in its own type annotation. +tests/cases/compiler/circularAccessorAnnotations.ts(6,9): error TS2502: 'foo' is referenced directly or indirectly in its own type annotation. +tests/cases/compiler/circularAccessorAnnotations.ts(15,9): error TS2502: 'foo' is referenced directly or indirectly in its own type annotation. +tests/cases/compiler/circularAccessorAnnotations.ts(19,9): error TS2502: 'foo' is referenced directly or indirectly in its own type annotation. + + +==== tests/cases/compiler/circularAccessorAnnotations.ts (4 errors) ==== + declare const c1: { + get foo(): typeof c1.foo; + ~~~ +!!! error TS2502: 'foo' is referenced directly or indirectly in its own type annotation. + } + + declare const c2: { + set foo(value: typeof c2.foo); + ~~~ +!!! error TS2502: 'foo' is referenced directly or indirectly in its own type annotation. + } + + declare const c3: { + get foo(): string; + set foo(value: typeof c3.foo); + } + + type T1 = { + get foo(): T1["foo"]; + ~~~ +!!! error TS2502: 'foo' is referenced directly or indirectly in its own type annotation. + } + + type T2 = { + set foo(value: T2["foo"]); + ~~~ +!!! error TS2502: 'foo' is referenced directly or indirectly in its own type annotation. + } + + type T3 = { + get foo(): string; + set foo(value: T3["foo"]); + } + \ No newline at end of file diff --git a/tests/baselines/reference/circularAccessorAnnotations.js b/tests/baselines/reference/circularAccessorAnnotations.js new file mode 100644 index 00000000000..2cdb41d7fa2 --- /dev/null +++ b/tests/baselines/reference/circularAccessorAnnotations.js @@ -0,0 +1,53 @@ +//// [circularAccessorAnnotations.ts] +declare const c1: { + get foo(): typeof c1.foo; +} + +declare const c2: { + set foo(value: typeof c2.foo); +} + +declare const c3: { + get foo(): string; + set foo(value: typeof c3.foo); +} + +type T1 = { + get foo(): T1["foo"]; +} + +type T2 = { + set foo(value: T2["foo"]); +} + +type T3 = { + get foo(): string; + set foo(value: T3["foo"]); +} + + +//// [circularAccessorAnnotations.js] +"use strict"; + + +//// [circularAccessorAnnotations.d.ts] +declare const c1: { + get foo(): typeof c1.foo; +}; +declare const c2: { + set foo(value: typeof c2.foo); +}; +declare const c3: { + get foo(): string; + set foo(value: typeof c3.foo); +}; +declare type T1 = { + get foo(): T1["foo"]; +}; +declare type T2 = { + set foo(value: T2["foo"]); +}; +declare type T3 = { + get foo(): string; + set foo(value: T3["foo"]); +}; diff --git a/tests/baselines/reference/circularAccessorAnnotations.symbols b/tests/baselines/reference/circularAccessorAnnotations.symbols new file mode 100644 index 00000000000..b3514fc1ea4 --- /dev/null +++ b/tests/baselines/reference/circularAccessorAnnotations.symbols @@ -0,0 +1,65 @@ +=== tests/cases/compiler/circularAccessorAnnotations.ts === +declare const c1: { +>c1 : Symbol(c1, Decl(circularAccessorAnnotations.ts, 0, 13)) + + get foo(): typeof c1.foo; +>foo : Symbol(foo, Decl(circularAccessorAnnotations.ts, 0, 19)) +>c1.foo : Symbol(foo, Decl(circularAccessorAnnotations.ts, 0, 19)) +>c1 : Symbol(c1, Decl(circularAccessorAnnotations.ts, 0, 13)) +>foo : Symbol(foo, Decl(circularAccessorAnnotations.ts, 0, 19)) +} + +declare const c2: { +>c2 : Symbol(c2, Decl(circularAccessorAnnotations.ts, 4, 13)) + + set foo(value: typeof c2.foo); +>foo : Symbol(foo, Decl(circularAccessorAnnotations.ts, 4, 19)) +>value : Symbol(value, Decl(circularAccessorAnnotations.ts, 5, 12)) +>c2.foo : Symbol(foo, Decl(circularAccessorAnnotations.ts, 4, 19)) +>c2 : Symbol(c2, Decl(circularAccessorAnnotations.ts, 4, 13)) +>foo : Symbol(foo, Decl(circularAccessorAnnotations.ts, 4, 19)) +} + +declare const c3: { +>c3 : Symbol(c3, Decl(circularAccessorAnnotations.ts, 8, 13)) + + get foo(): string; +>foo : Symbol(foo, Decl(circularAccessorAnnotations.ts, 8, 19), Decl(circularAccessorAnnotations.ts, 9, 22)) + + set foo(value: typeof c3.foo); +>foo : Symbol(foo, Decl(circularAccessorAnnotations.ts, 8, 19), Decl(circularAccessorAnnotations.ts, 9, 22)) +>value : Symbol(value, Decl(circularAccessorAnnotations.ts, 10, 12)) +>c3.foo : Symbol(foo, Decl(circularAccessorAnnotations.ts, 8, 19), Decl(circularAccessorAnnotations.ts, 9, 22)) +>c3 : Symbol(c3, Decl(circularAccessorAnnotations.ts, 8, 13)) +>foo : Symbol(foo, Decl(circularAccessorAnnotations.ts, 8, 19), Decl(circularAccessorAnnotations.ts, 9, 22)) +} + +type T1 = { +>T1 : Symbol(T1, Decl(circularAccessorAnnotations.ts, 11, 1)) + + get foo(): T1["foo"]; +>foo : Symbol(foo, Decl(circularAccessorAnnotations.ts, 13, 11)) +>T1 : Symbol(T1, Decl(circularAccessorAnnotations.ts, 11, 1)) +} + +type T2 = { +>T2 : Symbol(T2, Decl(circularAccessorAnnotations.ts, 15, 1)) + + set foo(value: T2["foo"]); +>foo : Symbol(foo, Decl(circularAccessorAnnotations.ts, 17, 11)) +>value : Symbol(value, Decl(circularAccessorAnnotations.ts, 18, 12)) +>T2 : Symbol(T2, Decl(circularAccessorAnnotations.ts, 15, 1)) +} + +type T3 = { +>T3 : Symbol(T3, Decl(circularAccessorAnnotations.ts, 19, 1)) + + get foo(): string; +>foo : Symbol(foo, Decl(circularAccessorAnnotations.ts, 21, 11), Decl(circularAccessorAnnotations.ts, 22, 22)) + + set foo(value: T3["foo"]); +>foo : Symbol(foo, Decl(circularAccessorAnnotations.ts, 21, 11), Decl(circularAccessorAnnotations.ts, 22, 22)) +>value : Symbol(value, Decl(circularAccessorAnnotations.ts, 23, 12)) +>T3 : Symbol(T3, Decl(circularAccessorAnnotations.ts, 19, 1)) +} + diff --git a/tests/baselines/reference/circularAccessorAnnotations.types b/tests/baselines/reference/circularAccessorAnnotations.types new file mode 100644 index 00000000000..1945fdc5109 --- /dev/null +++ b/tests/baselines/reference/circularAccessorAnnotations.types @@ -0,0 +1,62 @@ +=== tests/cases/compiler/circularAccessorAnnotations.ts === +declare const c1: { +>c1 : { readonly foo: any; } + + get foo(): typeof c1.foo; +>foo : any +>c1.foo : any +>c1 : { readonly foo: any; } +>foo : any +} + +declare const c2: { +>c2 : { foo: any; } + + set foo(value: typeof c2.foo); +>foo : any +>value : any +>c2.foo : any +>c2 : { foo: any; } +>foo : any +} + +declare const c3: { +>c3 : { foo: string; } + + get foo(): string; +>foo : string + + set foo(value: typeof c3.foo); +>foo : string +>value : string +>c3.foo : string +>c3 : { foo: string; } +>foo : string +} + +type T1 = { +>T1 : T1 + + get foo(): T1["foo"]; +>foo : any +} + +type T2 = { +>T2 : T2 + + set foo(value: T2["foo"]); +>foo : any +>value : any +} + +type T3 = { +>T3 : T3 + + get foo(): string; +>foo : string + + set foo(value: T3["foo"]); +>foo : string +>value : string +} + diff --git a/tests/baselines/reference/circularGetAccessor(noimplicitany=false).errors.txt b/tests/baselines/reference/circularGetAccessor(noimplicitany=false).errors.txt new file mode 100644 index 00000000000..b616c1ad8bf --- /dev/null +++ b/tests/baselines/reference/circularGetAccessor(noimplicitany=false).errors.txt @@ -0,0 +1,10 @@ +tests/cases/compiler/circularGetAccessor.ts(2,9): error TS2502: 'foo' is referenced directly or indirectly in its own type annotation. + + +==== tests/cases/compiler/circularGetAccessor.ts (1 errors) ==== + declare class C { + get foo(): typeof this.foo; + ~~~ +!!! error TS2502: 'foo' is referenced directly or indirectly in its own type annotation. + } + \ No newline at end of file diff --git a/tests/baselines/reference/circularGetAccessor(noimplicitany=false).js b/tests/baselines/reference/circularGetAccessor(noimplicitany=false).js new file mode 100644 index 00000000000..ffe5c03a85d --- /dev/null +++ b/tests/baselines/reference/circularGetAccessor(noimplicitany=false).js @@ -0,0 +1,7 @@ +//// [circularGetAccessor.ts] +declare class C { + get foo(): typeof this.foo; +} + + +//// [circularGetAccessor.js] diff --git a/tests/baselines/reference/circularGetAccessor(noimplicitany=false).symbols b/tests/baselines/reference/circularGetAccessor(noimplicitany=false).symbols new file mode 100644 index 00000000000..0afc5b19d1e --- /dev/null +++ b/tests/baselines/reference/circularGetAccessor(noimplicitany=false).symbols @@ -0,0 +1,11 @@ +=== tests/cases/compiler/circularGetAccessor.ts === +declare class C { +>C : Symbol(C, Decl(circularGetAccessor.ts, 0, 0)) + + get foo(): typeof this.foo; +>foo : Symbol(C.foo, Decl(circularGetAccessor.ts, 0, 17)) +>this.foo : Symbol(C.foo, Decl(circularGetAccessor.ts, 0, 17)) +>this : Symbol(C, Decl(circularGetAccessor.ts, 0, 0)) +>foo : Symbol(C.foo, Decl(circularGetAccessor.ts, 0, 17)) +} + diff --git a/tests/baselines/reference/circularGetAccessor(noimplicitany=false).types b/tests/baselines/reference/circularGetAccessor(noimplicitany=false).types new file mode 100644 index 00000000000..bb7527742c7 --- /dev/null +++ b/tests/baselines/reference/circularGetAccessor(noimplicitany=false).types @@ -0,0 +1,11 @@ +=== tests/cases/compiler/circularGetAccessor.ts === +declare class C { +>C : C + + get foo(): typeof this.foo; +>foo : any +>this.foo : any +>this : this +>foo : any +} + diff --git a/tests/baselines/reference/circularGetAccessor(noimplicitany=true).errors.txt b/tests/baselines/reference/circularGetAccessor(noimplicitany=true).errors.txt new file mode 100644 index 00000000000..b616c1ad8bf --- /dev/null +++ b/tests/baselines/reference/circularGetAccessor(noimplicitany=true).errors.txt @@ -0,0 +1,10 @@ +tests/cases/compiler/circularGetAccessor.ts(2,9): error TS2502: 'foo' is referenced directly or indirectly in its own type annotation. + + +==== tests/cases/compiler/circularGetAccessor.ts (1 errors) ==== + declare class C { + get foo(): typeof this.foo; + ~~~ +!!! error TS2502: 'foo' is referenced directly or indirectly in its own type annotation. + } + \ No newline at end of file diff --git a/tests/baselines/reference/circularGetAccessor(noimplicitany=true).js b/tests/baselines/reference/circularGetAccessor(noimplicitany=true).js new file mode 100644 index 00000000000..ffe5c03a85d --- /dev/null +++ b/tests/baselines/reference/circularGetAccessor(noimplicitany=true).js @@ -0,0 +1,7 @@ +//// [circularGetAccessor.ts] +declare class C { + get foo(): typeof this.foo; +} + + +//// [circularGetAccessor.js] diff --git a/tests/baselines/reference/circularGetAccessor(noimplicitany=true).symbols b/tests/baselines/reference/circularGetAccessor(noimplicitany=true).symbols new file mode 100644 index 00000000000..0afc5b19d1e --- /dev/null +++ b/tests/baselines/reference/circularGetAccessor(noimplicitany=true).symbols @@ -0,0 +1,11 @@ +=== tests/cases/compiler/circularGetAccessor.ts === +declare class C { +>C : Symbol(C, Decl(circularGetAccessor.ts, 0, 0)) + + get foo(): typeof this.foo; +>foo : Symbol(C.foo, Decl(circularGetAccessor.ts, 0, 17)) +>this.foo : Symbol(C.foo, Decl(circularGetAccessor.ts, 0, 17)) +>this : Symbol(C, Decl(circularGetAccessor.ts, 0, 0)) +>foo : Symbol(C.foo, Decl(circularGetAccessor.ts, 0, 17)) +} + diff --git a/tests/baselines/reference/circularGetAccessor(noimplicitany=true).types b/tests/baselines/reference/circularGetAccessor(noimplicitany=true).types new file mode 100644 index 00000000000..bb7527742c7 --- /dev/null +++ b/tests/baselines/reference/circularGetAccessor(noimplicitany=true).types @@ -0,0 +1,11 @@ +=== tests/cases/compiler/circularGetAccessor.ts === +declare class C { +>C : C + + get foo(): typeof this.foo; +>foo : any +>this.foo : any +>this : this +>foo : any +} + diff --git a/tests/baselines/reference/circularIndexedAccessErrors.errors.txt b/tests/baselines/reference/circularIndexedAccessErrors.errors.txt index f2bf858ab9e..3bd2d323f1c 100644 --- a/tests/baselines/reference/circularIndexedAccessErrors.errors.txt +++ b/tests/baselines/reference/circularIndexedAccessErrors.errors.txt @@ -1,5 +1,5 @@ tests/cases/conformance/types/keyof/circularIndexedAccessErrors.ts(2,5): error TS2502: 'x' is referenced directly or indirectly in its own type annotation. -tests/cases/conformance/types/keyof/circularIndexedAccessErrors.ts(6,5): error TS2502: 'x' is referenced directly or indirectly in its own type annotation. +tests/cases/conformance/types/keyof/circularIndexedAccessErrors.ts(11,11): error TS2589: Type instantiation is excessively deep and possibly infinite. tests/cases/conformance/types/keyof/circularIndexedAccessErrors.ts(18,5): error TS2502: 'x' is referenced directly or indirectly in its own type annotation. tests/cases/conformance/types/keyof/circularIndexedAccessErrors.ts(22,5): error TS2502: 'x' is referenced directly or indirectly in its own type annotation. tests/cases/conformance/types/keyof/circularIndexedAccessErrors.ts(37,24): error TS2313: Type parameter 'T' has a circular constraint. @@ -15,13 +15,13 @@ tests/cases/conformance/types/keyof/circularIndexedAccessErrors.ts(37,30): error type T2 = { x: T2[K]; // Error - ~ -!!! error TS2502: 'x' is referenced directly or indirectly in its own type annotation. y: number; } declare let x2: T2<"x">; let x2x = x2.x; + ~~~~ +!!! error TS2589: Type instantiation is excessively deep and possibly infinite. interface T3> { x: T["x"]; diff --git a/tests/baselines/reference/classStaticBlock28.js b/tests/baselines/reference/classStaticBlock28.js new file mode 100644 index 00000000000..955dc88d3cf --- /dev/null +++ b/tests/baselines/reference/classStaticBlock28.js @@ -0,0 +1,23 @@ +//// [classStaticBlock28.ts] +let foo: number; + +class C { + static { + foo = 1 + } +} + +console.log(foo) + +//// [classStaticBlock28.js] +"use strict"; +var foo; +var C = /** @class */ (function () { + function C() { + } + return C; +}()); +(function () { + foo = 1; +})(); +console.log(foo); diff --git a/tests/baselines/reference/classStaticBlock28.symbols b/tests/baselines/reference/classStaticBlock28.symbols new file mode 100644 index 00000000000..3a8dc99b9d1 --- /dev/null +++ b/tests/baselines/reference/classStaticBlock28.symbols @@ -0,0 +1,19 @@ +=== tests/cases/conformance/classes/classStaticBlock/classStaticBlock28.ts === +let foo: number; +>foo : Symbol(foo, Decl(classStaticBlock28.ts, 0, 3)) + +class C { +>C : Symbol(C, Decl(classStaticBlock28.ts, 0, 16)) + + static { + foo = 1 +>foo : Symbol(foo, Decl(classStaticBlock28.ts, 0, 3)) + } +} + +console.log(foo) +>console.log : Symbol(Console.log, Decl(lib.dom.d.ts, --, --)) +>console : Symbol(console, Decl(lib.dom.d.ts, --, --)) +>log : Symbol(Console.log, Decl(lib.dom.d.ts, --, --)) +>foo : Symbol(foo, Decl(classStaticBlock28.ts, 0, 3)) + diff --git a/tests/baselines/reference/classStaticBlock28.types b/tests/baselines/reference/classStaticBlock28.types new file mode 100644 index 00000000000..8abbe617d9f --- /dev/null +++ b/tests/baselines/reference/classStaticBlock28.types @@ -0,0 +1,22 @@ +=== tests/cases/conformance/classes/classStaticBlock/classStaticBlock28.ts === +let foo: number; +>foo : number + +class C { +>C : C + + static { + foo = 1 +>foo = 1 : 1 +>foo : number +>1 : 1 + } +} + +console.log(foo) +>console.log(foo) : void +>console.log : (...data: any[]) => void +>console : Console +>log : (...data: any[]) => void +>foo : number + diff --git a/tests/baselines/reference/classStaticBlockUseBeforeDef3.errors.txt b/tests/baselines/reference/classStaticBlockUseBeforeDef3.errors.txt new file mode 100644 index 00000000000..7fed7444b57 --- /dev/null +++ b/tests/baselines/reference/classStaticBlockUseBeforeDef3.errors.txt @@ -0,0 +1,53 @@ +tests/cases/conformance/classes/classStaticBlock/classStaticBlockUseBeforeDef3.ts(14,21): error TS2448: Block-scoped variable 'FOO' used before its declaration. +tests/cases/conformance/classes/classStaticBlock/classStaticBlockUseBeforeDef3.ts(14,21): error TS2454: Variable 'FOO' is used before being assigned. + + +==== tests/cases/conformance/classes/classStaticBlock/classStaticBlockUseBeforeDef3.ts (2 errors) ==== + class A { + static { + A.doSomething(); // should not error + } + + static doSomething() { + console.log("gotcha!"); + } + } + + + class Baz { + static { + console.log(FOO); // should error + ~~~ +!!! error TS2448: Block-scoped variable 'FOO' used before its declaration. +!!! related TS2728 tests/cases/conformance/classes/classStaticBlock/classStaticBlockUseBeforeDef3.ts:18:7: 'FOO' is declared here. + ~~~ +!!! error TS2454: Variable 'FOO' is used before being assigned. + } + } + + const FOO = "FOO"; + class Bar { + static { + console.log(FOO); // should not error + } + } + + let u = "FOO" as "FOO" | "BAR"; + + class CFA { + static { + u = "BAR"; + u; // should be "BAR" + } + + static t = 1; + + static doSomething() {} + + static { + u; // should be "BAR" + } + } + + u; // should be "BAR" + \ No newline at end of file diff --git a/tests/baselines/reference/classStaticBlockUseBeforeDef3.symbols b/tests/baselines/reference/classStaticBlockUseBeforeDef3.symbols new file mode 100644 index 00000000000..beb214dab08 --- /dev/null +++ b/tests/baselines/reference/classStaticBlockUseBeforeDef3.symbols @@ -0,0 +1,78 @@ +=== tests/cases/conformance/classes/classStaticBlock/classStaticBlockUseBeforeDef3.ts === +class A { +>A : Symbol(A, Decl(classStaticBlockUseBeforeDef3.ts, 0, 0)) + + static { + A.doSomething(); // should not error +>A.doSomething : Symbol(A.doSomething, Decl(classStaticBlockUseBeforeDef3.ts, 3, 5)) +>A : Symbol(A, Decl(classStaticBlockUseBeforeDef3.ts, 0, 0)) +>doSomething : Symbol(A.doSomething, Decl(classStaticBlockUseBeforeDef3.ts, 3, 5)) + } + + static doSomething() { +>doSomething : Symbol(A.doSomething, Decl(classStaticBlockUseBeforeDef3.ts, 3, 5)) + + console.log("gotcha!"); +>console.log : Symbol(Console.log, Decl(lib.dom.d.ts, --, --)) +>console : Symbol(console, Decl(lib.dom.d.ts, --, --)) +>log : Symbol(Console.log, Decl(lib.dom.d.ts, --, --)) + } +} + + +class Baz { +>Baz : Symbol(Baz, Decl(classStaticBlockUseBeforeDef3.ts, 8, 1)) + + static { + console.log(FOO); // should error +>console.log : Symbol(Console.log, Decl(lib.dom.d.ts, --, --)) +>console : Symbol(console, Decl(lib.dom.d.ts, --, --)) +>log : Symbol(Console.log, Decl(lib.dom.d.ts, --, --)) +>FOO : Symbol(FOO, Decl(classStaticBlockUseBeforeDef3.ts, 17, 5)) + } +} + +const FOO = "FOO"; +>FOO : Symbol(FOO, Decl(classStaticBlockUseBeforeDef3.ts, 17, 5)) + +class Bar { +>Bar : Symbol(Bar, Decl(classStaticBlockUseBeforeDef3.ts, 17, 18)) + + static { + console.log(FOO); // should not error +>console.log : Symbol(Console.log, Decl(lib.dom.d.ts, --, --)) +>console : Symbol(console, Decl(lib.dom.d.ts, --, --)) +>log : Symbol(Console.log, Decl(lib.dom.d.ts, --, --)) +>FOO : Symbol(FOO, Decl(classStaticBlockUseBeforeDef3.ts, 17, 5)) + } +} + +let u = "FOO" as "FOO" | "BAR"; +>u : Symbol(u, Decl(classStaticBlockUseBeforeDef3.ts, 24, 3)) + +class CFA { +>CFA : Symbol(CFA, Decl(classStaticBlockUseBeforeDef3.ts, 24, 31)) + + static { + u = "BAR"; +>u : Symbol(u, Decl(classStaticBlockUseBeforeDef3.ts, 24, 3)) + + u; // should be "BAR" +>u : Symbol(u, Decl(classStaticBlockUseBeforeDef3.ts, 24, 3)) + } + + static t = 1; +>t : Symbol(CFA.t, Decl(classStaticBlockUseBeforeDef3.ts, 30, 5)) + + static doSomething() {} +>doSomething : Symbol(CFA.doSomething, Decl(classStaticBlockUseBeforeDef3.ts, 32, 17)) + + static { + u; // should be "BAR" +>u : Symbol(u, Decl(classStaticBlockUseBeforeDef3.ts, 24, 3)) + } +} + +u; // should be "BAR" +>u : Symbol(u, Decl(classStaticBlockUseBeforeDef3.ts, 24, 3)) + diff --git a/tests/baselines/reference/classStaticBlockUseBeforeDef3.types b/tests/baselines/reference/classStaticBlockUseBeforeDef3.types new file mode 100644 index 00000000000..f10c2ee0f67 --- /dev/null +++ b/tests/baselines/reference/classStaticBlockUseBeforeDef3.types @@ -0,0 +1,89 @@ +=== tests/cases/conformance/classes/classStaticBlock/classStaticBlockUseBeforeDef3.ts === +class A { +>A : A + + static { + A.doSomething(); // should not error +>A.doSomething() : void +>A.doSomething : () => void +>A : typeof A +>doSomething : () => void + } + + static doSomething() { +>doSomething : () => void + + console.log("gotcha!"); +>console.log("gotcha!") : void +>console.log : (...data: any[]) => void +>console : Console +>log : (...data: any[]) => void +>"gotcha!" : "gotcha!" + } +} + + +class Baz { +>Baz : Baz + + static { + console.log(FOO); // should error +>console.log(FOO) : void +>console.log : (...data: any[]) => void +>console : Console +>log : (...data: any[]) => void +>FOO : "FOO" + } +} + +const FOO = "FOO"; +>FOO : "FOO" +>"FOO" : "FOO" + +class Bar { +>Bar : Bar + + static { + console.log(FOO); // should not error +>console.log(FOO) : void +>console.log : (...data: any[]) => void +>console : Console +>log : (...data: any[]) => void +>FOO : "FOO" + } +} + +let u = "FOO" as "FOO" | "BAR"; +>u : "FOO" | "BAR" +>"FOO" as "FOO" | "BAR" : "FOO" | "BAR" +>"FOO" : "FOO" + +class CFA { +>CFA : CFA + + static { + u = "BAR"; +>u = "BAR" : "BAR" +>u : "FOO" | "BAR" +>"BAR" : "BAR" + + u; // should be "BAR" +>u : "BAR" + } + + static t = 1; +>t : number +>1 : 1 + + static doSomething() {} +>doSomething : () => void + + static { + u; // should be "BAR" +>u : "BAR" + } +} + +u; // should be "BAR" +>u : "BAR" + diff --git a/tests/baselines/reference/completionsCommentsClass.baseline b/tests/baselines/reference/completionsCommentsClass.baseline index b16322debe6..5f4294590d9 100644 --- a/tests/baselines/reference/completionsCommentsClass.baseline +++ b/tests/baselines/reference/completionsCommentsClass.baseline @@ -3760,7 +3760,7 @@ "name": "escape", "kind": "function", "kindModifiers": "deprecated,declare", - "sortText": "23", + "sortText": "24", "displayParts": [ { "text": "function", @@ -3850,7 +3850,7 @@ "name": "unescape", "kind": "function", "kindModifiers": "deprecated,declare", - "sortText": "23", + "sortText": "24", "displayParts": [ { "text": "function", diff --git a/tests/baselines/reference/completionsCommentsClassMembers.baseline b/tests/baselines/reference/completionsCommentsClassMembers.baseline index 8a4468b7da9..0486ae6854a 100644 --- a/tests/baselines/reference/completionsCommentsClassMembers.baseline +++ b/tests/baselines/reference/completionsCommentsClassMembers.baseline @@ -4632,7 +4632,7 @@ "name": "escape", "kind": "function", "kindModifiers": "deprecated,declare", - "sortText": "23", + "sortText": "24", "displayParts": [ { "text": "function", @@ -4722,7 +4722,7 @@ "name": "unescape", "kind": "function", "kindModifiers": "deprecated,declare", - "sortText": "23", + "sortText": "24", "displayParts": [ { "text": "function", @@ -11688,7 +11688,7 @@ "name": "escape", "kind": "function", "kindModifiers": "deprecated,declare", - "sortText": "23", + "sortText": "24", "displayParts": [ { "text": "function", @@ -11778,7 +11778,7 @@ "name": "unescape", "kind": "function", "kindModifiers": "deprecated,declare", - "sortText": "23", + "sortText": "24", "displayParts": [ { "text": "function", @@ -16500,7 +16500,7 @@ "name": "escape", "kind": "function", "kindModifiers": "deprecated,declare", - "sortText": "23", + "sortText": "24", "displayParts": [ { "text": "function", @@ -16590,7 +16590,7 @@ "name": "unescape", "kind": "function", "kindModifiers": "deprecated,declare", - "sortText": "23", + "sortText": "24", "displayParts": [ { "text": "function", @@ -23556,7 +23556,7 @@ "name": "escape", "kind": "function", "kindModifiers": "deprecated,declare", - "sortText": "23", + "sortText": "24", "displayParts": [ { "text": "function", @@ -23646,7 +23646,7 @@ "name": "unescape", "kind": "function", "kindModifiers": "deprecated,declare", - "sortText": "23", + "sortText": "24", "displayParts": [ { "text": "function", @@ -27620,7 +27620,7 @@ "name": "escape", "kind": "function", "kindModifiers": "deprecated,declare", - "sortText": "23", + "sortText": "24", "displayParts": [ { "text": "function", @@ -27710,7 +27710,7 @@ "name": "unescape", "kind": "function", "kindModifiers": "deprecated,declare", - "sortText": "23", + "sortText": "24", "displayParts": [ { "text": "function", @@ -32839,7 +32839,7 @@ "name": "escape", "kind": "function", "kindModifiers": "deprecated,declare", - "sortText": "23", + "sortText": "24", "displayParts": [ { "text": "function", @@ -32929,7 +32929,7 @@ "name": "unescape", "kind": "function", "kindModifiers": "deprecated,declare", - "sortText": "23", + "sortText": "24", "displayParts": [ { "text": "function", @@ -36857,7 +36857,7 @@ "name": "escape", "kind": "function", "kindModifiers": "deprecated,declare", - "sortText": "23", + "sortText": "24", "displayParts": [ { "text": "function", @@ -36947,7 +36947,7 @@ "name": "unescape", "kind": "function", "kindModifiers": "deprecated,declare", - "sortText": "23", + "sortText": "24", "displayParts": [ { "text": "function", @@ -42030,7 +42030,7 @@ "name": "escape", "kind": "function", "kindModifiers": "deprecated,declare", - "sortText": "23", + "sortText": "24", "displayParts": [ { "text": "function", @@ -42120,7 +42120,7 @@ "name": "unescape", "kind": "function", "kindModifiers": "deprecated,declare", - "sortText": "23", + "sortText": "24", "displayParts": [ { "text": "function", @@ -47249,7 +47249,7 @@ "name": "escape", "kind": "function", "kindModifiers": "deprecated,declare", - "sortText": "23", + "sortText": "24", "displayParts": [ { "text": "function", @@ -47339,7 +47339,7 @@ "name": "unescape", "kind": "function", "kindModifiers": "deprecated,declare", - "sortText": "23", + "sortText": "24", "displayParts": [ { "text": "function", @@ -52468,7 +52468,7 @@ "name": "escape", "kind": "function", "kindModifiers": "deprecated,declare", - "sortText": "23", + "sortText": "24", "displayParts": [ { "text": "function", @@ -52558,7 +52558,7 @@ "name": "unescape", "kind": "function", "kindModifiers": "deprecated,declare", - "sortText": "23", + "sortText": "24", "displayParts": [ { "text": "function", @@ -57687,7 +57687,7 @@ "name": "escape", "kind": "function", "kindModifiers": "deprecated,declare", - "sortText": "23", + "sortText": "24", "displayParts": [ { "text": "function", @@ -57777,7 +57777,7 @@ "name": "unescape", "kind": "function", "kindModifiers": "deprecated,declare", - "sortText": "23", + "sortText": "24", "displayParts": [ { "text": "function", @@ -61746,7 +61746,7 @@ "name": "escape", "kind": "function", "kindModifiers": "deprecated,declare", - "sortText": "23", + "sortText": "24", "displayParts": [ { "text": "function", @@ -61836,7 +61836,7 @@ "name": "unescape", "kind": "function", "kindModifiers": "deprecated,declare", - "sortText": "23", + "sortText": "24", "displayParts": [ { "text": "function", @@ -65805,7 +65805,7 @@ "name": "escape", "kind": "function", "kindModifiers": "deprecated,declare", - "sortText": "23", + "sortText": "24", "displayParts": [ { "text": "function", @@ -65895,7 +65895,7 @@ "name": "unescape", "kind": "function", "kindModifiers": "deprecated,declare", - "sortText": "23", + "sortText": "24", "displayParts": [ { "text": "function", @@ -69864,7 +69864,7 @@ "name": "escape", "kind": "function", "kindModifiers": "deprecated,declare", - "sortText": "23", + "sortText": "24", "displayParts": [ { "text": "function", @@ -69954,7 +69954,7 @@ "name": "unescape", "kind": "function", "kindModifiers": "deprecated,declare", - "sortText": "23", + "sortText": "24", "displayParts": [ { "text": "function", @@ -73923,7 +73923,7 @@ "name": "escape", "kind": "function", "kindModifiers": "deprecated,declare", - "sortText": "23", + "sortText": "24", "displayParts": [ { "text": "function", @@ -74013,7 +74013,7 @@ "name": "unescape", "kind": "function", "kindModifiers": "deprecated,declare", - "sortText": "23", + "sortText": "24", "displayParts": [ { "text": "function", @@ -77982,7 +77982,7 @@ "name": "escape", "kind": "function", "kindModifiers": "deprecated,declare", - "sortText": "23", + "sortText": "24", "displayParts": [ { "text": "function", @@ -78072,7 +78072,7 @@ "name": "unescape", "kind": "function", "kindModifiers": "deprecated,declare", - "sortText": "23", + "sortText": "24", "displayParts": [ { "text": "function", @@ -82041,7 +82041,7 @@ "name": "escape", "kind": "function", "kindModifiers": "deprecated,declare", - "sortText": "23", + "sortText": "24", "displayParts": [ { "text": "function", @@ -82131,7 +82131,7 @@ "name": "unescape", "kind": "function", "kindModifiers": "deprecated,declare", - "sortText": "23", + "sortText": "24", "displayParts": [ { "text": "function", @@ -86596,7 +86596,7 @@ "name": "escape", "kind": "function", "kindModifiers": "deprecated,declare", - "sortText": "23", + "sortText": "24", "displayParts": [ { "text": "function", @@ -86686,7 +86686,7 @@ "name": "unescape", "kind": "function", "kindModifiers": "deprecated,declare", - "sortText": "23", + "sortText": "24", "displayParts": [ { "text": "function", @@ -91952,7 +91952,7 @@ "name": "escape", "kind": "function", "kindModifiers": "deprecated,declare", - "sortText": "23", + "sortText": "24", "displayParts": [ { "text": "function", @@ -92042,7 +92042,7 @@ "name": "unescape", "kind": "function", "kindModifiers": "deprecated,declare", - "sortText": "23", + "sortText": "24", "displayParts": [ { "text": "function", @@ -96407,7 +96407,7 @@ "name": "escape", "kind": "function", "kindModifiers": "deprecated,declare", - "sortText": "23", + "sortText": "24", "displayParts": [ { "text": "function", @@ -96497,7 +96497,7 @@ "name": "unescape", "kind": "function", "kindModifiers": "deprecated,declare", - "sortText": "23", + "sortText": "24", "displayParts": [ { "text": "function", diff --git a/tests/baselines/reference/completionsCommentsCommentParsing.baseline b/tests/baselines/reference/completionsCommentsCommentParsing.baseline index 66e9516361e..ea44b2c255f 100644 --- a/tests/baselines/reference/completionsCommentsCommentParsing.baseline +++ b/tests/baselines/reference/completionsCommentsCommentParsing.baseline @@ -5467,7 +5467,7 @@ "name": "escape", "kind": "function", "kindModifiers": "deprecated,declare", - "sortText": "23", + "sortText": "24", "displayParts": [ { "text": "function", @@ -5557,7 +5557,7 @@ "name": "unescape", "kind": "function", "kindModifiers": "deprecated,declare", - "sortText": "23", + "sortText": "24", "displayParts": [ { "text": "function", @@ -11910,7 +11910,7 @@ "name": "escape", "kind": "function", "kindModifiers": "deprecated,declare", - "sortText": "23", + "sortText": "24", "displayParts": [ { "text": "function", @@ -12000,7 +12000,7 @@ "name": "unescape", "kind": "function", "kindModifiers": "deprecated,declare", - "sortText": "23", + "sortText": "24", "displayParts": [ { "text": "function", @@ -17533,7 +17533,7 @@ "name": "escape", "kind": "function", "kindModifiers": "deprecated,declare", - "sortText": "23", + "sortText": "24", "displayParts": [ { "text": "function", @@ -17623,7 +17623,7 @@ "name": "unescape", "kind": "function", "kindModifiers": "deprecated,declare", - "sortText": "23", + "sortText": "24", "displayParts": [ { "text": "function", @@ -23233,7 +23233,7 @@ "name": "escape", "kind": "function", "kindModifiers": "deprecated,declare", - "sortText": "23", + "sortText": "24", "displayParts": [ { "text": "function", @@ -23323,7 +23323,7 @@ "name": "unescape", "kind": "function", "kindModifiers": "deprecated,declare", - "sortText": "23", + "sortText": "24", "displayParts": [ { "text": "function", @@ -28975,7 +28975,7 @@ "name": "escape", "kind": "function", "kindModifiers": "deprecated,declare", - "sortText": "23", + "sortText": "24", "displayParts": [ { "text": "function", @@ -29065,7 +29065,7 @@ "name": "unescape", "kind": "function", "kindModifiers": "deprecated,declare", - "sortText": "23", + "sortText": "24", "displayParts": [ { "text": "function", @@ -35418,7 +35418,7 @@ "name": "escape", "kind": "function", "kindModifiers": "deprecated,declare", - "sortText": "23", + "sortText": "24", "displayParts": [ { "text": "function", @@ -35508,7 +35508,7 @@ "name": "unescape", "kind": "function", "kindModifiers": "deprecated,declare", - "sortText": "23", + "sortText": "24", "displayParts": [ { "text": "function", @@ -41118,7 +41118,7 @@ "name": "escape", "kind": "function", "kindModifiers": "deprecated,declare", - "sortText": "23", + "sortText": "24", "displayParts": [ { "text": "function", @@ -41208,7 +41208,7 @@ "name": "unescape", "kind": "function", "kindModifiers": "deprecated,declare", - "sortText": "23", + "sortText": "24", "displayParts": [ { "text": "function", diff --git a/tests/baselines/reference/completionsCommentsFunctionDeclaration.baseline b/tests/baselines/reference/completionsCommentsFunctionDeclaration.baseline index 7a58a4e801d..9f0294c4e82 100644 --- a/tests/baselines/reference/completionsCommentsFunctionDeclaration.baseline +++ b/tests/baselines/reference/completionsCommentsFunctionDeclaration.baseline @@ -4130,7 +4130,7 @@ "name": "escape", "kind": "function", "kindModifiers": "deprecated,declare", - "sortText": "23", + "sortText": "24", "displayParts": [ { "text": "function", @@ -4220,7 +4220,7 @@ "name": "unescape", "kind": "function", "kindModifiers": "deprecated,declare", - "sortText": "23", + "sortText": "24", "displayParts": [ { "text": "function", @@ -7606,7 +7606,7 @@ "name": "escape", "kind": "function", "kindModifiers": "deprecated,declare", - "sortText": "23", + "sortText": "24", "displayParts": [ { "text": "function", @@ -7696,7 +7696,7 @@ "name": "unescape", "kind": "function", "kindModifiers": "deprecated,declare", - "sortText": "23", + "sortText": "24", "displayParts": [ { "text": "function", @@ -11916,7 +11916,7 @@ "name": "escape", "kind": "function", "kindModifiers": "deprecated,declare", - "sortText": "23", + "sortText": "24", "displayParts": [ { "text": "function", @@ -12006,7 +12006,7 @@ "name": "unescape", "kind": "function", "kindModifiers": "deprecated,declare", - "sortText": "23", + "sortText": "24", "displayParts": [ { "text": "function", diff --git a/tests/baselines/reference/completionsCommentsFunctionExpression.baseline b/tests/baselines/reference/completionsCommentsFunctionExpression.baseline index 6184a312462..ddada8f7b64 100644 --- a/tests/baselines/reference/completionsCommentsFunctionExpression.baseline +++ b/tests/baselines/reference/completionsCommentsFunctionExpression.baseline @@ -3667,7 +3667,7 @@ "name": "escape", "kind": "function", "kindModifiers": "deprecated,declare", - "sortText": "23", + "sortText": "24", "displayParts": [ { "text": "function", @@ -3757,7 +3757,7 @@ "name": "unescape", "kind": "function", "kindModifiers": "deprecated,declare", - "sortText": "23", + "sortText": "24", "displayParts": [ { "text": "function", @@ -8389,7 +8389,7 @@ "name": "escape", "kind": "function", "kindModifiers": "deprecated,declare", - "sortText": "23", + "sortText": "24", "displayParts": [ { "text": "function", @@ -8479,7 +8479,7 @@ "name": "unescape", "kind": "function", "kindModifiers": "deprecated,declare", - "sortText": "23", + "sortText": "24", "displayParts": [ { "text": "function", @@ -12055,7 +12055,7 @@ "name": "escape", "kind": "function", "kindModifiers": "deprecated,declare", - "sortText": "23", + "sortText": "24", "displayParts": [ { "text": "function", @@ -12145,7 +12145,7 @@ "name": "unescape", "kind": "function", "kindModifiers": "deprecated,declare", - "sortText": "23", + "sortText": "24", "displayParts": [ { "text": "function", @@ -16549,7 +16549,7 @@ "name": "escape", "kind": "function", "kindModifiers": "deprecated,declare", - "sortText": "23", + "sortText": "24", "displayParts": [ { "text": "function", @@ -16639,7 +16639,7 @@ "name": "unescape", "kind": "function", "kindModifiers": "deprecated,declare", - "sortText": "23", + "sortText": "24", "displayParts": [ { "text": "function", diff --git a/tests/baselines/reference/completionsSalsaMethodsOnAssignedFunctionExpressions.baseline b/tests/baselines/reference/completionsSalsaMethodsOnAssignedFunctionExpressions.baseline index 373d25682df..4c5bcf2c68d 100644 --- a/tests/baselines/reference/completionsSalsaMethodsOnAssignedFunctionExpressions.baseline +++ b/tests/baselines/reference/completionsSalsaMethodsOnAssignedFunctionExpressions.baseline @@ -127,35 +127,35 @@ "name": "a", "kind": "warning", "kindModifiers": "", - "sortText": "17", + "sortText": "18", "isFromUncheckedFile": true }, { "name": "C", "kind": "warning", "kindModifiers": "", - "sortText": "17", + "sortText": "18", "isFromUncheckedFile": true }, { "name": "f", "kind": "warning", "kindModifiers": "", - "sortText": "17", + "sortText": "18", "isFromUncheckedFile": true }, { "name": "prototype", "kind": "warning", "kindModifiers": "", - "sortText": "17", + "sortText": "18", "isFromUncheckedFile": true }, { "name": "x", "kind": "warning", "kindModifiers": "", - "sortText": "17", + "sortText": "18", "isFromUncheckedFile": true } ] diff --git a/tests/baselines/reference/completionsStringMethods.baseline b/tests/baselines/reference/completionsStringMethods.baseline index fdf01f72da3..4e12c7480ab 100644 --- a/tests/baselines/reference/completionsStringMethods.baseline +++ b/tests/baselines/reference/completionsStringMethods.baseline @@ -2164,7 +2164,7 @@ "name": "substr", "kind": "method", "kindModifiers": "deprecated,declare", - "sortText": "19", + "sortText": "20", "displayParts": [ { "text": "(", diff --git a/tests/baselines/reference/discriminantPropertyInference.js b/tests/baselines/reference/discriminantPropertyInference.js index e65bf3869b0..96f6a106a11 100644 --- a/tests/baselines/reference/discriminantPropertyInference.js +++ b/tests/baselines/reference/discriminantPropertyInference.js @@ -11,9 +11,7 @@ type DiscriminatorFalse = { cb: (x: number) => void; } -type Unrelated = { - val: number; -} +type Props = DiscriminatorTrue | DiscriminatorFalse; declare function f(options: DiscriminatorTrue | DiscriminatorFalse): any; @@ -39,14 +37,6 @@ f({ f({ cb: n => n.toFixed() }); - - -declare function g(options: DiscriminatorTrue | DiscriminatorFalse | Unrelated): any; - -// requires checking properties of all types, rather than properties of just the union type (e.g. only intersection) -g({ - cb: n => n.toFixed() -}); //// [discriminantPropertyInference.js] @@ -70,7 +60,3 @@ f({ f({ cb: function (n) { return n.toFixed(); } }); -// requires checking properties of all types, rather than properties of just the union type (e.g. only intersection) -g({ - cb: function (n) { return n.toFixed(); } -}); diff --git a/tests/baselines/reference/discriminantPropertyInference.symbols b/tests/baselines/reference/discriminantPropertyInference.symbols index 938ce86b0c2..1908bdd9843 100644 --- a/tests/baselines/reference/discriminantPropertyInference.symbols +++ b/tests/baselines/reference/discriminantPropertyInference.symbols @@ -23,97 +23,74 @@ type DiscriminatorFalse = { >x : Symbol(x, Decl(discriminantPropertyInference.ts, 9, 9)) } -type Unrelated = { ->Unrelated : Symbol(Unrelated, Decl(discriminantPropertyInference.ts, 10, 1)) - - val: number; ->val : Symbol(val, Decl(discriminantPropertyInference.ts, 12, 18)) -} +type Props = DiscriminatorTrue | DiscriminatorFalse; +>Props : Symbol(Props, Decl(discriminantPropertyInference.ts, 10, 1)) +>DiscriminatorTrue : Symbol(DiscriminatorTrue, Decl(discriminantPropertyInference.ts, 0, 0)) +>DiscriminatorFalse : Symbol(DiscriminatorFalse, Decl(discriminantPropertyInference.ts, 5, 1)) declare function f(options: DiscriminatorTrue | DiscriminatorFalse): any; ->f : Symbol(f, Decl(discriminantPropertyInference.ts, 14, 1)) ->options : Symbol(options, Decl(discriminantPropertyInference.ts, 16, 19)) +>f : Symbol(f, Decl(discriminantPropertyInference.ts, 12, 52)) +>options : Symbol(options, Decl(discriminantPropertyInference.ts, 14, 19)) >DiscriminatorTrue : Symbol(DiscriminatorTrue, Decl(discriminantPropertyInference.ts, 0, 0)) >DiscriminatorFalse : Symbol(DiscriminatorFalse, Decl(discriminantPropertyInference.ts, 5, 1)) // simple inference f({ ->f : Symbol(f, Decl(discriminantPropertyInference.ts, 14, 1)) +>f : Symbol(f, Decl(discriminantPropertyInference.ts, 12, 52)) disc: true, ->disc : Symbol(disc, Decl(discriminantPropertyInference.ts, 19, 3)) +>disc : Symbol(disc, Decl(discriminantPropertyInference.ts, 17, 3)) cb: s => parseInt(s) ->cb : Symbol(cb, Decl(discriminantPropertyInference.ts, 20, 15)) ->s : Symbol(s, Decl(discriminantPropertyInference.ts, 21, 7)) +>cb : Symbol(cb, Decl(discriminantPropertyInference.ts, 18, 15)) +>s : Symbol(s, Decl(discriminantPropertyInference.ts, 19, 7)) >parseInt : Symbol(parseInt, Decl(lib.es5.d.ts, --, --)) ->s : Symbol(s, Decl(discriminantPropertyInference.ts, 21, 7)) +>s : Symbol(s, Decl(discriminantPropertyInference.ts, 19, 7)) }); // simple inference f({ ->f : Symbol(f, Decl(discriminantPropertyInference.ts, 14, 1)) +>f : Symbol(f, Decl(discriminantPropertyInference.ts, 12, 52)) disc: false, ->disc : Symbol(disc, Decl(discriminantPropertyInference.ts, 25, 3)) +>disc : Symbol(disc, Decl(discriminantPropertyInference.ts, 23, 3)) cb: n => n.toFixed() ->cb : Symbol(cb, Decl(discriminantPropertyInference.ts, 26, 16)) ->n : Symbol(n, Decl(discriminantPropertyInference.ts, 27, 7)) +>cb : Symbol(cb, Decl(discriminantPropertyInference.ts, 24, 16)) +>n : Symbol(n, Decl(discriminantPropertyInference.ts, 25, 7)) >n.toFixed : Symbol(Number.toFixed, Decl(lib.es5.d.ts, --, --)) ->n : Symbol(n, Decl(discriminantPropertyInference.ts, 27, 7)) +>n : Symbol(n, Decl(discriminantPropertyInference.ts, 25, 7)) >toFixed : Symbol(Number.toFixed, Decl(lib.es5.d.ts, --, --)) }); // simple inference when strict-null-checks are enabled f({ ->f : Symbol(f, Decl(discriminantPropertyInference.ts, 14, 1)) +>f : Symbol(f, Decl(discriminantPropertyInference.ts, 12, 52)) disc: undefined, ->disc : Symbol(disc, Decl(discriminantPropertyInference.ts, 31, 3)) +>disc : Symbol(disc, Decl(discriminantPropertyInference.ts, 29, 3)) >undefined : Symbol(undefined) cb: n => n.toFixed() ->cb : Symbol(cb, Decl(discriminantPropertyInference.ts, 32, 20)) ->n : Symbol(n, Decl(discriminantPropertyInference.ts, 33, 7)) +>cb : Symbol(cb, Decl(discriminantPropertyInference.ts, 30, 20)) +>n : Symbol(n, Decl(discriminantPropertyInference.ts, 31, 7)) >n.toFixed : Symbol(Number.toFixed, Decl(lib.es5.d.ts, --, --)) ->n : Symbol(n, Decl(discriminantPropertyInference.ts, 33, 7)) +>n : Symbol(n, Decl(discriminantPropertyInference.ts, 31, 7)) >toFixed : Symbol(Number.toFixed, Decl(lib.es5.d.ts, --, --)) }); // requires checking type information since discriminator is missing from object f({ ->f : Symbol(f, Decl(discriminantPropertyInference.ts, 14, 1)) +>f : Symbol(f, Decl(discriminantPropertyInference.ts, 12, 52)) cb: n => n.toFixed() ->cb : Symbol(cb, Decl(discriminantPropertyInference.ts, 37, 3)) ->n : Symbol(n, Decl(discriminantPropertyInference.ts, 38, 7)) +>cb : Symbol(cb, Decl(discriminantPropertyInference.ts, 35, 3)) +>n : Symbol(n, Decl(discriminantPropertyInference.ts, 36, 7)) >n.toFixed : Symbol(Number.toFixed, Decl(lib.es5.d.ts, --, --)) ->n : Symbol(n, Decl(discriminantPropertyInference.ts, 38, 7)) ->toFixed : Symbol(Number.toFixed, Decl(lib.es5.d.ts, --, --)) - -}); - - -declare function g(options: DiscriminatorTrue | DiscriminatorFalse | Unrelated): any; ->g : Symbol(g, Decl(discriminantPropertyInference.ts, 39, 3)) ->options : Symbol(options, Decl(discriminantPropertyInference.ts, 42, 19)) ->DiscriminatorTrue : Symbol(DiscriminatorTrue, Decl(discriminantPropertyInference.ts, 0, 0)) ->DiscriminatorFalse : Symbol(DiscriminatorFalse, Decl(discriminantPropertyInference.ts, 5, 1)) ->Unrelated : Symbol(Unrelated, Decl(discriminantPropertyInference.ts, 10, 1)) - -// requires checking properties of all types, rather than properties of just the union type (e.g. only intersection) -g({ ->g : Symbol(g, Decl(discriminantPropertyInference.ts, 39, 3)) - - cb: n => n.toFixed() ->cb : Symbol(cb, Decl(discriminantPropertyInference.ts, 45, 3)) ->n : Symbol(n, Decl(discriminantPropertyInference.ts, 46, 7)) ->n.toFixed : Symbol(Number.toFixed, Decl(lib.es5.d.ts, --, --)) ->n : Symbol(n, Decl(discriminantPropertyInference.ts, 46, 7)) +>n : Symbol(n, Decl(discriminantPropertyInference.ts, 36, 7)) >toFixed : Symbol(Number.toFixed, Decl(lib.es5.d.ts, --, --)) }); diff --git a/tests/baselines/reference/discriminantPropertyInference.types b/tests/baselines/reference/discriminantPropertyInference.types index eef51e40a17..2ebc6c6a373 100644 --- a/tests/baselines/reference/discriminantPropertyInference.types +++ b/tests/baselines/reference/discriminantPropertyInference.types @@ -25,12 +25,8 @@ type DiscriminatorFalse = { >x : number } -type Unrelated = { ->Unrelated : Unrelated - - val: number; ->val : number -} +type Props = DiscriminatorTrue | DiscriminatorFalse; +>Props : Props declare function f(options: DiscriminatorTrue | DiscriminatorFalse): any; >f : (options: DiscriminatorTrue | DiscriminatorFalse) => any @@ -115,25 +111,3 @@ f({ }); - -declare function g(options: DiscriminatorTrue | DiscriminatorFalse | Unrelated): any; ->g : (options: DiscriminatorTrue | DiscriminatorFalse | Unrelated) => any ->options : DiscriminatorTrue | DiscriminatorFalse | Unrelated - -// requires checking properties of all types, rather than properties of just the union type (e.g. only intersection) -g({ ->g({ cb: n => n.toFixed()}) : any ->g : (options: DiscriminatorTrue | DiscriminatorFalse | Unrelated) => any ->{ cb: n => n.toFixed()} : { cb: (n: number) => string; } - - cb: n => n.toFixed() ->cb : (n: number) => string ->n => n.toFixed() : (n: number) => string ->n : number ->n.toFixed() : string ->n.toFixed : (fractionDigits?: number | undefined) => string ->n : number ->toFixed : (fractionDigits?: number | undefined) => string - -}); - diff --git a/tests/baselines/reference/emitDecoratorMetadata_isolatedModules(module=commonjs).js b/tests/baselines/reference/emitDecoratorMetadata_isolatedModules(module=commonjs).js new file mode 100644 index 00000000000..83510c98289 --- /dev/null +++ b/tests/baselines/reference/emitDecoratorMetadata_isolatedModules(module=commonjs).js @@ -0,0 +1,108 @@ +//// [tests/cases/compiler/emitDecoratorMetadata_isolatedModules.ts] //// + +//// [type1.ts] +interface T1 {} +export type { T1 } + +//// [type2.ts] +export interface T2 {} + +//// [class3.ts] +export class C3 {} + +//// [index.ts] +import { T1 } from "./type1"; +import * as t1 from "./type1"; +import type { T2 } from "./type2"; +import { C3 } from "./class3"; +declare var EventListener: any; + +class HelloWorld { + @EventListener('1') + handleEvent1(event: T1) {} // Error + + @EventListener('2') + handleEvent2(event: T2) {} // Ok + + @EventListener('1') + p1!: T1; // Error + + @EventListener('1') + p1_ns!: t1.T1; // Ok + + @EventListener('2') + p2!: T2; // Ok + + @EventListener('3') + handleEvent3(event: C3): T1 { return undefined! } // Ok, Error +} + + +//// [type1.js] +"use strict"; +exports.__esModule = true; +//// [type2.js] +"use strict"; +exports.__esModule = true; +//// [class3.js] +"use strict"; +exports.__esModule = true; +exports.C3 = void 0; +var C3 = /** @class */ (function () { + function C3() { + } + return C3; +}()); +exports.C3 = C3; +//// [index.js] +"use strict"; +var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; +}; +var __metadata = (this && this.__metadata) || function (k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); +}; +exports.__esModule = true; +var t1 = require("./type1"); +var class3_1 = require("./class3"); +var HelloWorld = /** @class */ (function () { + function HelloWorld() { + } + HelloWorld.prototype.handleEvent1 = function (event) { }; // Error + HelloWorld.prototype.handleEvent2 = function (event) { }; // Ok + HelloWorld.prototype.handleEvent3 = function (event) { return undefined; }; // Ok, Error + __decorate([ + EventListener('1'), + __metadata("design:type", Function), + __metadata("design:paramtypes", [Object]), + __metadata("design:returntype", void 0) + ], HelloWorld.prototype, "handleEvent1"); + __decorate([ + EventListener('2'), + __metadata("design:type", Function), + __metadata("design:paramtypes", [Object]), + __metadata("design:returntype", void 0) + ], HelloWorld.prototype, "handleEvent2"); + __decorate([ + EventListener('1'), + __metadata("design:type", Object) + ], HelloWorld.prototype, "p1"); + __decorate([ + EventListener('1'), + __metadata("design:type", Object) + ], HelloWorld.prototype, "p1_ns"); + __decorate([ + EventListener('2'), + __metadata("design:type", Object) + ], HelloWorld.prototype, "p2"); + __decorate([ + EventListener('3'), + __metadata("design:type", Function), + __metadata("design:paramtypes", [class3_1.C3]), + __metadata("design:returntype", Object) + ], HelloWorld.prototype, "handleEvent3"); + return HelloWorld; +}()); diff --git a/tests/baselines/reference/emitDecoratorMetadata_isolatedModules(module=commonjs).symbols b/tests/baselines/reference/emitDecoratorMetadata_isolatedModules(module=commonjs).symbols new file mode 100644 index 00000000000..075bdc3ee78 --- /dev/null +++ b/tests/baselines/reference/emitDecoratorMetadata_isolatedModules(module=commonjs).symbols @@ -0,0 +1,83 @@ +=== tests/cases/compiler/type1.ts === +interface T1 {} +>T1 : Symbol(T1, Decl(type1.ts, 0, 0)) + +export type { T1 } +>T1 : Symbol(T1, Decl(type1.ts, 1, 13)) + +=== tests/cases/compiler/type2.ts === +export interface T2 {} +>T2 : Symbol(T2, Decl(type2.ts, 0, 0)) + +=== tests/cases/compiler/class3.ts === +export class C3 {} +>C3 : Symbol(C3, Decl(class3.ts, 0, 0)) + +=== tests/cases/compiler/index.ts === +import { T1 } from "./type1"; +>T1 : Symbol(T1, Decl(index.ts, 0, 8)) + +import * as t1 from "./type1"; +>t1 : Symbol(t1, Decl(index.ts, 1, 6)) + +import type { T2 } from "./type2"; +>T2 : Symbol(T2, Decl(index.ts, 2, 13)) + +import { C3 } from "./class3"; +>C3 : Symbol(C3, Decl(index.ts, 3, 8)) + +declare var EventListener: any; +>EventListener : Symbol(EventListener, Decl(index.ts, 4, 11)) + +class HelloWorld { +>HelloWorld : Symbol(HelloWorld, Decl(index.ts, 4, 31)) + + @EventListener('1') +>EventListener : Symbol(EventListener, Decl(index.ts, 4, 11)) + + handleEvent1(event: T1) {} // Error +>handleEvent1 : Symbol(HelloWorld.handleEvent1, Decl(index.ts, 6, 18)) +>event : Symbol(event, Decl(index.ts, 8, 15)) +>T1 : Symbol(T1, Decl(index.ts, 0, 8)) + + @EventListener('2') +>EventListener : Symbol(EventListener, Decl(index.ts, 4, 11)) + + handleEvent2(event: T2) {} // Ok +>handleEvent2 : Symbol(HelloWorld.handleEvent2, Decl(index.ts, 8, 28)) +>event : Symbol(event, Decl(index.ts, 11, 15)) +>T2 : Symbol(T2, Decl(index.ts, 2, 13)) + + @EventListener('1') +>EventListener : Symbol(EventListener, Decl(index.ts, 4, 11)) + + p1!: T1; // Error +>p1 : Symbol(HelloWorld.p1, Decl(index.ts, 11, 28)) +>T1 : Symbol(T1, Decl(index.ts, 0, 8)) + + @EventListener('1') +>EventListener : Symbol(EventListener, Decl(index.ts, 4, 11)) + + p1_ns!: t1.T1; // Ok +>p1_ns : Symbol(HelloWorld.p1_ns, Decl(index.ts, 14, 10)) +>t1 : Symbol(t1, Decl(index.ts, 1, 6)) +>T1 : Symbol(t1.T1, Decl(type1.ts, 1, 13)) + + @EventListener('2') +>EventListener : Symbol(EventListener, Decl(index.ts, 4, 11)) + + p2!: T2; // Ok +>p2 : Symbol(HelloWorld.p2, Decl(index.ts, 17, 16)) +>T2 : Symbol(T2, Decl(index.ts, 2, 13)) + + @EventListener('3') +>EventListener : Symbol(EventListener, Decl(index.ts, 4, 11)) + + handleEvent3(event: C3): T1 { return undefined! } // Ok, Error +>handleEvent3 : Symbol(HelloWorld.handleEvent3, Decl(index.ts, 20, 10)) +>event : Symbol(event, Decl(index.ts, 23, 15)) +>C3 : Symbol(C3, Decl(index.ts, 3, 8)) +>T1 : Symbol(T1, Decl(index.ts, 0, 8)) +>undefined : Symbol(undefined) +} + diff --git a/tests/baselines/reference/emitDecoratorMetadata_isolatedModules(module=commonjs).types b/tests/baselines/reference/emitDecoratorMetadata_isolatedModules(module=commonjs).types new file mode 100644 index 00000000000..b2615eac81b --- /dev/null +++ b/tests/baselines/reference/emitDecoratorMetadata_isolatedModules(module=commonjs).types @@ -0,0 +1,86 @@ +=== tests/cases/compiler/type1.ts === +interface T1 {} +export type { T1 } +>T1 : T1 + +=== tests/cases/compiler/type2.ts === +export interface T2 {} +No type information for this code. +No type information for this code.=== tests/cases/compiler/class3.ts === +export class C3 {} +>C3 : C3 + +=== tests/cases/compiler/index.ts === +import { T1 } from "./type1"; +>T1 : any + +import * as t1 from "./type1"; +>t1 : typeof t1 + +import type { T2 } from "./type2"; +>T2 : T2 + +import { C3 } from "./class3"; +>C3 : typeof C3 + +declare var EventListener: any; +>EventListener : any + +class HelloWorld { +>HelloWorld : HelloWorld + + @EventListener('1') +>EventListener('1') : any +>EventListener : any +>'1' : "1" + + handleEvent1(event: T1) {} // Error +>handleEvent1 : (event: T1) => void +>event : T1 + + @EventListener('2') +>EventListener('2') : any +>EventListener : any +>'2' : "2" + + handleEvent2(event: T2) {} // Ok +>handleEvent2 : (event: T2) => void +>event : T2 + + @EventListener('1') +>EventListener('1') : any +>EventListener : any +>'1' : "1" + + p1!: T1; // Error +>p1 : T1 + + @EventListener('1') +>EventListener('1') : any +>EventListener : any +>'1' : "1" + + p1_ns!: t1.T1; // Ok +>p1_ns : T1 +>t1 : any + + @EventListener('2') +>EventListener('2') : any +>EventListener : any +>'2' : "2" + + p2!: T2; // Ok +>p2 : T2 + + @EventListener('3') +>EventListener('3') : any +>EventListener : any +>'3' : "3" + + handleEvent3(event: C3): T1 { return undefined! } // Ok, Error +>handleEvent3 : (event: C3) => T1 +>event : C3 +>undefined! : undefined +>undefined : undefined +} + diff --git a/tests/baselines/reference/emitDecoratorMetadata_isolatedModules(module=esnext).errors.txt b/tests/baselines/reference/emitDecoratorMetadata_isolatedModules(module=esnext).errors.txt new file mode 100644 index 00000000000..5e7f959a506 --- /dev/null +++ b/tests/baselines/reference/emitDecoratorMetadata_isolatedModules(module=esnext).errors.txt @@ -0,0 +1,51 @@ +tests/cases/compiler/index.ts(9,23): error TS1272: A type referenced in a decorated signature must be imported with 'import type' or a namespace import when 'isolatedModules' and 'emitDecoratorMetadata' are enabled. +tests/cases/compiler/index.ts(15,8): error TS1272: A type referenced in a decorated signature must be imported with 'import type' or a namespace import when 'isolatedModules' and 'emitDecoratorMetadata' are enabled. +tests/cases/compiler/index.ts(24,28): error TS1272: A type referenced in a decorated signature must be imported with 'import type' or a namespace import when 'isolatedModules' and 'emitDecoratorMetadata' are enabled. + + +==== tests/cases/compiler/type1.ts (0 errors) ==== + interface T1 {} + export type { T1 } + +==== tests/cases/compiler/type2.ts (0 errors) ==== + export interface T2 {} + +==== tests/cases/compiler/class3.ts (0 errors) ==== + export class C3 {} + +==== tests/cases/compiler/index.ts (3 errors) ==== + import { T1 } from "./type1"; + import * as t1 from "./type1"; + import type { T2 } from "./type2"; + import { C3 } from "./class3"; + declare var EventListener: any; + + class HelloWorld { + @EventListener('1') + handleEvent1(event: T1) {} // Error + ~~ +!!! error TS1272: A type referenced in a decorated signature must be imported with 'import type' or a namespace import when 'isolatedModules' and 'emitDecoratorMetadata' are enabled. +!!! related TS1376 tests/cases/compiler/index.ts:1:10: 'T1' was imported here. + + @EventListener('2') + handleEvent2(event: T2) {} // Ok + + @EventListener('1') + p1!: T1; // Error + ~~ +!!! error TS1272: A type referenced in a decorated signature must be imported with 'import type' or a namespace import when 'isolatedModules' and 'emitDecoratorMetadata' are enabled. +!!! related TS1376 tests/cases/compiler/index.ts:1:10: 'T1' was imported here. + + @EventListener('1') + p1_ns!: t1.T1; // Ok + + @EventListener('2') + p2!: T2; // Ok + + @EventListener('3') + handleEvent3(event: C3): T1 { return undefined! } // Ok, Error + ~~ +!!! error TS1272: A type referenced in a decorated signature must be imported with 'import type' or a namespace import when 'isolatedModules' and 'emitDecoratorMetadata' are enabled. +!!! related TS1376 tests/cases/compiler/index.ts:1:10: 'T1' was imported here. + } + \ No newline at end of file diff --git a/tests/baselines/reference/emitDecoratorMetadata_isolatedModules(module=esnext).js b/tests/baselines/reference/emitDecoratorMetadata_isolatedModules(module=esnext).js new file mode 100644 index 00000000000..121f3be7031 --- /dev/null +++ b/tests/baselines/reference/emitDecoratorMetadata_isolatedModules(module=esnext).js @@ -0,0 +1,101 @@ +//// [tests/cases/compiler/emitDecoratorMetadata_isolatedModules.ts] //// + +//// [type1.ts] +interface T1 {} +export type { T1 } + +//// [type2.ts] +export interface T2 {} + +//// [class3.ts] +export class C3 {} + +//// [index.ts] +import { T1 } from "./type1"; +import * as t1 from "./type1"; +import type { T2 } from "./type2"; +import { C3 } from "./class3"; +declare var EventListener: any; + +class HelloWorld { + @EventListener('1') + handleEvent1(event: T1) {} // Error + + @EventListener('2') + handleEvent2(event: T2) {} // Ok + + @EventListener('1') + p1!: T1; // Error + + @EventListener('1') + p1_ns!: t1.T1; // Ok + + @EventListener('2') + p2!: T2; // Ok + + @EventListener('3') + handleEvent3(event: C3): T1 { return undefined! } // Ok, Error +} + + +//// [type1.js] +export {}; +//// [type2.js] +export {}; +//// [class3.js] +var C3 = /** @class */ (function () { + function C3() { + } + return C3; +}()); +export { C3 }; +//// [index.js] +var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; +}; +var __metadata = (this && this.__metadata) || function (k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); +}; +import * as t1 from "./type1"; +import { C3 } from "./class3"; +var HelloWorld = /** @class */ (function () { + function HelloWorld() { + } + HelloWorld.prototype.handleEvent1 = function (event) { }; // Error + HelloWorld.prototype.handleEvent2 = function (event) { }; // Ok + HelloWorld.prototype.handleEvent3 = function (event) { return undefined; }; // Ok, Error + __decorate([ + EventListener('1'), + __metadata("design:type", Function), + __metadata("design:paramtypes", [Object]), + __metadata("design:returntype", void 0) + ], HelloWorld.prototype, "handleEvent1"); + __decorate([ + EventListener('2'), + __metadata("design:type", Function), + __metadata("design:paramtypes", [Object]), + __metadata("design:returntype", void 0) + ], HelloWorld.prototype, "handleEvent2"); + __decorate([ + EventListener('1'), + __metadata("design:type", Object) + ], HelloWorld.prototype, "p1"); + __decorate([ + EventListener('1'), + __metadata("design:type", Object) + ], HelloWorld.prototype, "p1_ns"); + __decorate([ + EventListener('2'), + __metadata("design:type", Object) + ], HelloWorld.prototype, "p2"); + __decorate([ + EventListener('3'), + __metadata("design:type", Function), + __metadata("design:paramtypes", [C3]), + __metadata("design:returntype", Object) + ], HelloWorld.prototype, "handleEvent3"); + return HelloWorld; +}()); diff --git a/tests/baselines/reference/emitDecoratorMetadata_isolatedModules(module=esnext).symbols b/tests/baselines/reference/emitDecoratorMetadata_isolatedModules(module=esnext).symbols new file mode 100644 index 00000000000..075bdc3ee78 --- /dev/null +++ b/tests/baselines/reference/emitDecoratorMetadata_isolatedModules(module=esnext).symbols @@ -0,0 +1,83 @@ +=== tests/cases/compiler/type1.ts === +interface T1 {} +>T1 : Symbol(T1, Decl(type1.ts, 0, 0)) + +export type { T1 } +>T1 : Symbol(T1, Decl(type1.ts, 1, 13)) + +=== tests/cases/compiler/type2.ts === +export interface T2 {} +>T2 : Symbol(T2, Decl(type2.ts, 0, 0)) + +=== tests/cases/compiler/class3.ts === +export class C3 {} +>C3 : Symbol(C3, Decl(class3.ts, 0, 0)) + +=== tests/cases/compiler/index.ts === +import { T1 } from "./type1"; +>T1 : Symbol(T1, Decl(index.ts, 0, 8)) + +import * as t1 from "./type1"; +>t1 : Symbol(t1, Decl(index.ts, 1, 6)) + +import type { T2 } from "./type2"; +>T2 : Symbol(T2, Decl(index.ts, 2, 13)) + +import { C3 } from "./class3"; +>C3 : Symbol(C3, Decl(index.ts, 3, 8)) + +declare var EventListener: any; +>EventListener : Symbol(EventListener, Decl(index.ts, 4, 11)) + +class HelloWorld { +>HelloWorld : Symbol(HelloWorld, Decl(index.ts, 4, 31)) + + @EventListener('1') +>EventListener : Symbol(EventListener, Decl(index.ts, 4, 11)) + + handleEvent1(event: T1) {} // Error +>handleEvent1 : Symbol(HelloWorld.handleEvent1, Decl(index.ts, 6, 18)) +>event : Symbol(event, Decl(index.ts, 8, 15)) +>T1 : Symbol(T1, Decl(index.ts, 0, 8)) + + @EventListener('2') +>EventListener : Symbol(EventListener, Decl(index.ts, 4, 11)) + + handleEvent2(event: T2) {} // Ok +>handleEvent2 : Symbol(HelloWorld.handleEvent2, Decl(index.ts, 8, 28)) +>event : Symbol(event, Decl(index.ts, 11, 15)) +>T2 : Symbol(T2, Decl(index.ts, 2, 13)) + + @EventListener('1') +>EventListener : Symbol(EventListener, Decl(index.ts, 4, 11)) + + p1!: T1; // Error +>p1 : Symbol(HelloWorld.p1, Decl(index.ts, 11, 28)) +>T1 : Symbol(T1, Decl(index.ts, 0, 8)) + + @EventListener('1') +>EventListener : Symbol(EventListener, Decl(index.ts, 4, 11)) + + p1_ns!: t1.T1; // Ok +>p1_ns : Symbol(HelloWorld.p1_ns, Decl(index.ts, 14, 10)) +>t1 : Symbol(t1, Decl(index.ts, 1, 6)) +>T1 : Symbol(t1.T1, Decl(type1.ts, 1, 13)) + + @EventListener('2') +>EventListener : Symbol(EventListener, Decl(index.ts, 4, 11)) + + p2!: T2; // Ok +>p2 : Symbol(HelloWorld.p2, Decl(index.ts, 17, 16)) +>T2 : Symbol(T2, Decl(index.ts, 2, 13)) + + @EventListener('3') +>EventListener : Symbol(EventListener, Decl(index.ts, 4, 11)) + + handleEvent3(event: C3): T1 { return undefined! } // Ok, Error +>handleEvent3 : Symbol(HelloWorld.handleEvent3, Decl(index.ts, 20, 10)) +>event : Symbol(event, Decl(index.ts, 23, 15)) +>C3 : Symbol(C3, Decl(index.ts, 3, 8)) +>T1 : Symbol(T1, Decl(index.ts, 0, 8)) +>undefined : Symbol(undefined) +} + diff --git a/tests/baselines/reference/emitDecoratorMetadata_isolatedModules(module=esnext).types b/tests/baselines/reference/emitDecoratorMetadata_isolatedModules(module=esnext).types new file mode 100644 index 00000000000..b2615eac81b --- /dev/null +++ b/tests/baselines/reference/emitDecoratorMetadata_isolatedModules(module=esnext).types @@ -0,0 +1,86 @@ +=== tests/cases/compiler/type1.ts === +interface T1 {} +export type { T1 } +>T1 : T1 + +=== tests/cases/compiler/type2.ts === +export interface T2 {} +No type information for this code. +No type information for this code.=== tests/cases/compiler/class3.ts === +export class C3 {} +>C3 : C3 + +=== tests/cases/compiler/index.ts === +import { T1 } from "./type1"; +>T1 : any + +import * as t1 from "./type1"; +>t1 : typeof t1 + +import type { T2 } from "./type2"; +>T2 : T2 + +import { C3 } from "./class3"; +>C3 : typeof C3 + +declare var EventListener: any; +>EventListener : any + +class HelloWorld { +>HelloWorld : HelloWorld + + @EventListener('1') +>EventListener('1') : any +>EventListener : any +>'1' : "1" + + handleEvent1(event: T1) {} // Error +>handleEvent1 : (event: T1) => void +>event : T1 + + @EventListener('2') +>EventListener('2') : any +>EventListener : any +>'2' : "2" + + handleEvent2(event: T2) {} // Ok +>handleEvent2 : (event: T2) => void +>event : T2 + + @EventListener('1') +>EventListener('1') : any +>EventListener : any +>'1' : "1" + + p1!: T1; // Error +>p1 : T1 + + @EventListener('1') +>EventListener('1') : any +>EventListener : any +>'1' : "1" + + p1_ns!: t1.T1; // Ok +>p1_ns : T1 +>t1 : any + + @EventListener('2') +>EventListener('2') : any +>EventListener : any +>'2' : "2" + + p2!: T2; // Ok +>p2 : T2 + + @EventListener('3') +>EventListener('3') : any +>EventListener : any +>'3' : "3" + + handleEvent3(event: C3): T1 { return undefined! } // Ok, Error +>handleEvent3 : (event: C3) => T1 +>event : C3 +>undefined! : undefined +>undefined : undefined +} + diff --git a/tests/baselines/reference/emitDecoratorMetadata_isolatedModules.errors.txt b/tests/baselines/reference/emitDecoratorMetadata_isolatedModules.errors.txt new file mode 100644 index 00000000000..cabda9caa7e --- /dev/null +++ b/tests/baselines/reference/emitDecoratorMetadata_isolatedModules.errors.txt @@ -0,0 +1,47 @@ +tests/cases/compiler/index.ts(8,23): error TS1267: A type referenced in a decorated signature must be imported with 'import type' when 'isolatedModules' and 'emitDecoratorMetadata' are enabled. +tests/cases/compiler/index.ts(14,8): error TS1267: A type referenced in a decorated signature must be imported with 'import type' when 'isolatedModules' and 'emitDecoratorMetadata' are enabled. +tests/cases/compiler/index.ts(20,28): error TS1267: A type referenced in a decorated signature must be imported with 'import type' when 'isolatedModules' and 'emitDecoratorMetadata' are enabled. + + +==== tests/cases/compiler/type1.ts (0 errors) ==== + interface T1 {} + export type { T1 } + +==== tests/cases/compiler/type2.ts (0 errors) ==== + export interface T2 {} + +==== tests/cases/compiler/class3.ts (0 errors) ==== + export class C3 {} + +==== tests/cases/compiler/index.ts (3 errors) ==== + import { T1 } from "./type1"; + import type { T2 } from "./type2"; + import { C3 } from "./class3"; + declare var EventListener: any; + + class HelloWorld { + @EventListener('1') + handleEvent1(event: T1) {} // Error + ~~ +!!! error TS1267: A type referenced in a decorated signature must be imported with 'import type' when 'isolatedModules' and 'emitDecoratorMetadata' are enabled. +!!! related TS1376 tests/cases/compiler/index.ts:1:10: 'T1' was imported here. + + @EventListener('2') + handleEvent2(event: T2) {} // Ok + + @EventListener('1') + p1!: T1; // Error + ~~ +!!! error TS1267: A type referenced in a decorated signature must be imported with 'import type' when 'isolatedModules' and 'emitDecoratorMetadata' are enabled. +!!! related TS1376 tests/cases/compiler/index.ts:1:10: 'T1' was imported here. + + @EventListener('2') + p2!: T2; // Ok + + @EventListener('3') + handleEvent3(event: C3): T1 { return undefined! } // Ok, Error + ~~ +!!! error TS1267: A type referenced in a decorated signature must be imported with 'import type' when 'isolatedModules' and 'emitDecoratorMetadata' are enabled. +!!! related TS1376 tests/cases/compiler/index.ts:1:10: 'T1' was imported here. + } + \ No newline at end of file diff --git a/tests/baselines/reference/emitDecoratorMetadata_isolatedModules.js b/tests/baselines/reference/emitDecoratorMetadata_isolatedModules.js new file mode 100644 index 00000000000..bb5e71383f4 --- /dev/null +++ b/tests/baselines/reference/emitDecoratorMetadata_isolatedModules.js @@ -0,0 +1,99 @@ +//// [tests/cases/compiler/emitDecoratorMetadata_isolatedModules.ts] //// + +//// [type1.ts] +interface T1 {} +export type { T1 } + +//// [type2.ts] +export interface T2 {} + +//// [class3.ts] +export class C3 {} + +//// [index.ts] +import { T1 } from "./type1"; +import type { T2 } from "./type2"; +import { C3 } from "./class3"; +declare var EventListener: any; + +class HelloWorld { + @EventListener('1') + handleEvent1(event: T1) {} // Error + + @EventListener('2') + handleEvent2(event: T2) {} // Ok + + @EventListener('1') + p1!: T1; // Error + + @EventListener('2') + p2!: T2; // Ok + + @EventListener('3') + handleEvent3(event: C3): T1 { return undefined! } // Ok, Error +} + + +//// [type1.js] +"use strict"; +exports.__esModule = true; +//// [type2.js] +"use strict"; +exports.__esModule = true; +//// [class3.js] +"use strict"; +exports.__esModule = true; +exports.C3 = void 0; +var C3 = /** @class */ (function () { + function C3() { + } + return C3; +}()); +exports.C3 = C3; +//// [index.js] +"use strict"; +var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; +}; +var __metadata = (this && this.__metadata) || function (k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); +}; +exports.__esModule = true; +var class3_1 = require("./class3"); +var HelloWorld = /** @class */ (function () { + function HelloWorld() { + } + HelloWorld.prototype.handleEvent1 = function (event) { }; // Error + HelloWorld.prototype.handleEvent2 = function (event) { }; // Ok + HelloWorld.prototype.handleEvent3 = function (event) { return undefined; }; // Ok, Error + __decorate([ + EventListener('1'), + __metadata("design:type", Function), + __metadata("design:paramtypes", [Object]), + __metadata("design:returntype", void 0) + ], HelloWorld.prototype, "handleEvent1"); + __decorate([ + EventListener('2'), + __metadata("design:type", Function), + __metadata("design:paramtypes", [Object]), + __metadata("design:returntype", void 0) + ], HelloWorld.prototype, "handleEvent2"); + __decorate([ + EventListener('1'), + __metadata("design:type", Object) + ], HelloWorld.prototype, "p1"); + __decorate([ + EventListener('2'), + __metadata("design:type", Object) + ], HelloWorld.prototype, "p2"); + __decorate([ + EventListener('3'), + __metadata("design:type", Function), + __metadata("design:paramtypes", [class3_1.C3]), + __metadata("design:returntype", Object) + ], HelloWorld.prototype, "handleEvent3"); + return HelloWorld; +}()); diff --git a/tests/baselines/reference/emitDecoratorMetadata_isolatedModules.symbols b/tests/baselines/reference/emitDecoratorMetadata_isolatedModules.symbols new file mode 100644 index 00000000000..c957b1781e3 --- /dev/null +++ b/tests/baselines/reference/emitDecoratorMetadata_isolatedModules.symbols @@ -0,0 +1,72 @@ +=== tests/cases/compiler/type1.ts === +interface T1 {} +>T1 : Symbol(T1, Decl(type1.ts, 0, 0)) + +export type { T1 } +>T1 : Symbol(T1, Decl(type1.ts, 1, 13)) + +=== tests/cases/compiler/type2.ts === +export interface T2 {} +>T2 : Symbol(T2, Decl(type2.ts, 0, 0)) + +=== tests/cases/compiler/class3.ts === +export class C3 {} +>C3 : Symbol(C3, Decl(class3.ts, 0, 0)) + +=== tests/cases/compiler/index.ts === +import { T1 } from "./type1"; +>T1 : Symbol(T1, Decl(index.ts, 0, 8)) + +import type { T2 } from "./type2"; +>T2 : Symbol(T2, Decl(index.ts, 1, 13)) + +import { C3 } from "./class3"; +>C3 : Symbol(C3, Decl(index.ts, 2, 8)) + +declare var EventListener: any; +>EventListener : Symbol(EventListener, Decl(index.ts, 3, 11)) + +class HelloWorld { +>HelloWorld : Symbol(HelloWorld, Decl(index.ts, 3, 31)) + + @EventListener('1') +>EventListener : Symbol(EventListener, Decl(index.ts, 3, 11)) + + handleEvent1(event: T1) {} // Error +>handleEvent1 : Symbol(HelloWorld.handleEvent1, Decl(index.ts, 5, 18)) +>event : Symbol(event, Decl(index.ts, 7, 15)) +>T1 : Symbol(T1, Decl(index.ts, 0, 8)) + + @EventListener('2') +>EventListener : Symbol(EventListener, Decl(index.ts, 3, 11)) + + handleEvent2(event: T2) {} // Ok +>handleEvent2 : Symbol(HelloWorld.handleEvent2, Decl(index.ts, 7, 28)) +>event : Symbol(event, Decl(index.ts, 10, 15)) +>T2 : Symbol(T2, Decl(index.ts, 1, 13)) + + @EventListener('1') +>EventListener : Symbol(EventListener, Decl(index.ts, 3, 11)) + + p1!: T1; // Error +>p1 : Symbol(HelloWorld.p1, Decl(index.ts, 10, 28)) +>T1 : Symbol(T1, Decl(index.ts, 0, 8)) + + @EventListener('2') +>EventListener : Symbol(EventListener, Decl(index.ts, 3, 11)) + + p2!: T2; // Ok +>p2 : Symbol(HelloWorld.p2, Decl(index.ts, 13, 10)) +>T2 : Symbol(T2, Decl(index.ts, 1, 13)) + + @EventListener('3') +>EventListener : Symbol(EventListener, Decl(index.ts, 3, 11)) + + handleEvent3(event: C3): T1 { return undefined! } // Ok, Error +>handleEvent3 : Symbol(HelloWorld.handleEvent3, Decl(index.ts, 16, 10)) +>event : Symbol(event, Decl(index.ts, 19, 15)) +>C3 : Symbol(C3, Decl(index.ts, 2, 8)) +>T1 : Symbol(T1, Decl(index.ts, 0, 8)) +>undefined : Symbol(undefined) +} + diff --git a/tests/baselines/reference/emitDecoratorMetadata_isolatedModules.types b/tests/baselines/reference/emitDecoratorMetadata_isolatedModules.types new file mode 100644 index 00000000000..0048771bb4e --- /dev/null +++ b/tests/baselines/reference/emitDecoratorMetadata_isolatedModules.types @@ -0,0 +1,74 @@ +=== tests/cases/compiler/type1.ts === +interface T1 {} +export type { T1 } +>T1 : T1 + +=== tests/cases/compiler/type2.ts === +export interface T2 {} +No type information for this code. +No type information for this code.=== tests/cases/compiler/class3.ts === +export class C3 {} +>C3 : C3 + +=== tests/cases/compiler/index.ts === +import { T1 } from "./type1"; +>T1 : any + +import type { T2 } from "./type2"; +>T2 : T2 + +import { C3 } from "./class3"; +>C3 : typeof C3 + +declare var EventListener: any; +>EventListener : any + +class HelloWorld { +>HelloWorld : HelloWorld + + @EventListener('1') +>EventListener('1') : any +>EventListener : any +>'1' : "1" + + handleEvent1(event: T1) {} // Error +>handleEvent1 : (event: T1) => void +>event : T1 + + @EventListener('2') +>EventListener('2') : any +>EventListener : any +>'2' : "2" + + handleEvent2(event: T2) {} // Ok +>handleEvent2 : (event: T2) => void +>event : T2 + + @EventListener('1') +>EventListener('1') : any +>EventListener : any +>'1' : "1" + + p1!: T1; // Error +>p1 : T1 + + @EventListener('2') +>EventListener('2') : any +>EventListener : any +>'2' : "2" + + p2!: T2; // Ok +>p2 : T2 + + @EventListener('3') +>EventListener('3') : any +>EventListener : any +>'3' : "3" + + handleEvent3(event: C3): T1 { return undefined! } // Ok, Error +>handleEvent3 : (event: C3) => T1 +>event : C3 +>undefined! : undefined +>undefined : undefined +} + diff --git a/tests/baselines/reference/exportSpecifiers_js.errors.txt b/tests/baselines/reference/exportSpecifiers_js.errors.txt new file mode 100644 index 00000000000..7d8fdd6fe4a --- /dev/null +++ b/tests/baselines/reference/exportSpecifiers_js.errors.txt @@ -0,0 +1,9 @@ +tests/cases/conformance/externalModules/typeOnly/a.js(2,10): error TS8006: 'export...type' declarations can only be used in TypeScript files. + + +==== tests/cases/conformance/externalModules/typeOnly/a.js (1 errors) ==== + const foo = 0; + export { type foo }; + ~~~~~~~~ +!!! error TS8006: 'export...type' declarations can only be used in TypeScript files. + \ No newline at end of file diff --git a/tests/baselines/reference/exportSpecifiers_js.symbols b/tests/baselines/reference/exportSpecifiers_js.symbols new file mode 100644 index 00000000000..0652aca8a1c --- /dev/null +++ b/tests/baselines/reference/exportSpecifiers_js.symbols @@ -0,0 +1,7 @@ +=== tests/cases/conformance/externalModules/typeOnly/a.js === +const foo = 0; +>foo : Symbol(foo, Decl(a.js, 0, 5)) + +export { type foo }; +>foo : Symbol(foo, Decl(a.js, 1, 8)) + diff --git a/tests/baselines/reference/exportSpecifiers_js.types b/tests/baselines/reference/exportSpecifiers_js.types new file mode 100644 index 00000000000..0637788c059 --- /dev/null +++ b/tests/baselines/reference/exportSpecifiers_js.types @@ -0,0 +1,8 @@ +=== tests/cases/conformance/externalModules/typeOnly/a.js === +const foo = 0; +>foo : 0 +>0 : 0 + +export { type foo }; +>foo : 0 + diff --git a/tests/baselines/reference/extractConstant/extractConstant_PropertyName.js b/tests/baselines/reference/extractConstant/extractConstant_PropertyName.js new file mode 100644 index 00000000000..430a117c338 --- /dev/null +++ b/tests/baselines/reference/extractConstant/extractConstant_PropertyName.js @@ -0,0 +1,5 @@ +// ==ORIGINAL== +/*[#|*/x.y/*|]*/.z(); +// ==SCOPE::Extract to constant in enclosing scope== +const y = x.y; +/*RENAME*/y.z(); \ No newline at end of file diff --git a/tests/baselines/reference/extractConstant/extractConstant_PropertyName.ts b/tests/baselines/reference/extractConstant/extractConstant_PropertyName.ts new file mode 100644 index 00000000000..430a117c338 --- /dev/null +++ b/tests/baselines/reference/extractConstant/extractConstant_PropertyName.ts @@ -0,0 +1,5 @@ +// ==ORIGINAL== +/*[#|*/x.y/*|]*/.z(); +// ==SCOPE::Extract to constant in enclosing scope== +const y = x.y; +/*RENAME*/y.z(); \ No newline at end of file diff --git a/tests/baselines/reference/extractConstant/extractConstant_PropertyName_ExistingName.js b/tests/baselines/reference/extractConstant/extractConstant_PropertyName_ExistingName.js new file mode 100644 index 00000000000..b1e5fd385ba --- /dev/null +++ b/tests/baselines/reference/extractConstant/extractConstant_PropertyName_ExistingName.js @@ -0,0 +1,7 @@ +// ==ORIGINAL== +let y; +/*[#|*/x.y/*|]*/.z(); +// ==SCOPE::Extract to constant in enclosing scope== +let y; +const newLocal = x.y; +/*RENAME*/newLocal.z(); \ No newline at end of file diff --git a/tests/baselines/reference/extractConstant/extractConstant_PropertyName_ExistingName.ts b/tests/baselines/reference/extractConstant/extractConstant_PropertyName_ExistingName.ts new file mode 100644 index 00000000000..b1e5fd385ba --- /dev/null +++ b/tests/baselines/reference/extractConstant/extractConstant_PropertyName_ExistingName.ts @@ -0,0 +1,7 @@ +// ==ORIGINAL== +let y; +/*[#|*/x.y/*|]*/.z(); +// ==SCOPE::Extract to constant in enclosing scope== +let y; +const newLocal = x.y; +/*RENAME*/newLocal.z(); \ No newline at end of file diff --git a/tests/baselines/reference/extractConstant/extractConstant_PropertyName_Keyword.js b/tests/baselines/reference/extractConstant/extractConstant_PropertyName_Keyword.js new file mode 100644 index 00000000000..ae9029dd6df --- /dev/null +++ b/tests/baselines/reference/extractConstant/extractConstant_PropertyName_Keyword.js @@ -0,0 +1,5 @@ +// ==ORIGINAL== +/*[#|*/x.if/*|]*/.z(); +// ==SCOPE::Extract to constant in enclosing scope== +const newLocal = x.if; +/*RENAME*/newLocal.z(); \ No newline at end of file diff --git a/tests/baselines/reference/extractConstant/extractConstant_PropertyName_Keyword.ts b/tests/baselines/reference/extractConstant/extractConstant_PropertyName_Keyword.ts new file mode 100644 index 00000000000..ae9029dd6df --- /dev/null +++ b/tests/baselines/reference/extractConstant/extractConstant_PropertyName_Keyword.ts @@ -0,0 +1,5 @@ +// ==ORIGINAL== +/*[#|*/x.if/*|]*/.z(); +// ==SCOPE::Extract to constant in enclosing scope== +const newLocal = x.if; +/*RENAME*/newLocal.z(); \ No newline at end of file diff --git a/tests/baselines/reference/extractConstant/extractConstant_PropertyName_PrivateIdentifierKeyword.js b/tests/baselines/reference/extractConstant/extractConstant_PropertyName_PrivateIdentifierKeyword.js new file mode 100644 index 00000000000..171b47b6e88 --- /dev/null +++ b/tests/baselines/reference/extractConstant/extractConstant_PropertyName_PrivateIdentifierKeyword.js @@ -0,0 +1,5 @@ +// ==ORIGINAL== +/*[#|*/this.#if/*|]*/.z(); +// ==SCOPE::Extract to constant in enclosing scope== +const newLocal = this.#if; +/*RENAME*/newLocal.z(); \ No newline at end of file diff --git a/tests/baselines/reference/extractConstant/extractConstant_PropertyName_PrivateIdentifierKeyword.ts b/tests/baselines/reference/extractConstant/extractConstant_PropertyName_PrivateIdentifierKeyword.ts new file mode 100644 index 00000000000..171b47b6e88 --- /dev/null +++ b/tests/baselines/reference/extractConstant/extractConstant_PropertyName_PrivateIdentifierKeyword.ts @@ -0,0 +1,5 @@ +// ==ORIGINAL== +/*[#|*/this.#if/*|]*/.z(); +// ==SCOPE::Extract to constant in enclosing scope== +const newLocal = this.#if; +/*RENAME*/newLocal.z(); \ No newline at end of file diff --git a/tests/baselines/reference/findAllRefs_importType_js.1.baseline.jsonc b/tests/baselines/reference/findAllRefs_importType_js.1.baseline.jsonc index 072f0ac1ab9..194d24ed3ed 100644 --- a/tests/baselines/reference/findAllRefs_importType_js.1.baseline.jsonc +++ b/tests/baselines/reference/findAllRefs_importType_js.1.baseline.jsonc @@ -15,7 +15,7 @@ "containerName": "", "fileName": "/a.js", "kind": "local class", - "name": "(local class) C", + "name": "(local class) C\nmodule C", "textSpan": { "start": 23, "length": 1 @@ -37,6 +37,22 @@ "text": " ", "kind": "space" }, + { + "text": "C", + "kind": "className" + }, + { + "text": "\n", + "kind": "lineBreak" + }, + { + "text": "module", + "kind": "keyword" + }, + { + "text": " ", + "kind": "space" + }, { "text": "C", "kind": "className" diff --git a/tests/baselines/reference/genericUnboundedTypeParamAssignability.errors.txt b/tests/baselines/reference/genericUnboundedTypeParamAssignability.errors.txt new file mode 100644 index 00000000000..6d7b87ebd33 --- /dev/null +++ b/tests/baselines/reference/genericUnboundedTypeParamAssignability.errors.txt @@ -0,0 +1,36 @@ +tests/cases/compiler/genericUnboundedTypeParamAssignability.ts(2,5): error TS2339: Property 'toString' does not exist on type 'T'. +tests/cases/compiler/genericUnboundedTypeParamAssignability.ts(15,6): error TS2345: Argument of type 'T' is not assignable to parameter of type '{}'. +tests/cases/compiler/genericUnboundedTypeParamAssignability.ts(16,6): error TS2345: Argument of type 'T' is not assignable to parameter of type 'Record'. +tests/cases/compiler/genericUnboundedTypeParamAssignability.ts(17,5): error TS2339: Property 'toString' does not exist on type 'T'. + + +==== tests/cases/compiler/genericUnboundedTypeParamAssignability.ts (4 errors) ==== + function f1(o: T) { + o.toString(); // error + ~~~~~~~~ +!!! error TS2339: Property 'toString' does not exist on type 'T'. + } + + function f2(o: T) { + o.toString(); // no error + } + + function f3>(o: T) { + o.toString(); // no error + } + + function user(t: T) { + f1(t); + f2(t); // error in strict, unbounded T doesn't satisfy the constraint + ~ +!!! error TS2345: Argument of type 'T' is not assignable to parameter of type '{}'. +!!! related TS2208 tests/cases/compiler/genericUnboundedTypeParamAssignability.ts:13:15: This type parameter probably needs an `extends object` constraint. + f3(t); // error in strict, unbounded T doesn't satisfy the constraint + ~ +!!! error TS2345: Argument of type 'T' is not assignable to parameter of type 'Record'. +!!! related TS2208 tests/cases/compiler/genericUnboundedTypeParamAssignability.ts:13:15: This type parameter probably needs an `extends object` constraint. + t.toString(); // error, for the same reason as f1() + ~~~~~~~~ +!!! error TS2339: Property 'toString' does not exist on type 'T'. + } + \ No newline at end of file diff --git a/tests/baselines/reference/genericUnboundedTypeParamAssignability.js b/tests/baselines/reference/genericUnboundedTypeParamAssignability.js new file mode 100644 index 00000000000..9c13758f22b --- /dev/null +++ b/tests/baselines/reference/genericUnboundedTypeParamAssignability.js @@ -0,0 +1,38 @@ +//// [genericUnboundedTypeParamAssignability.ts] +function f1(o: T) { + o.toString(); // error +} + +function f2(o: T) { + o.toString(); // no error +} + +function f3>(o: T) { + o.toString(); // no error +} + +function user(t: T) { + f1(t); + f2(t); // error in strict, unbounded T doesn't satisfy the constraint + f3(t); // error in strict, unbounded T doesn't satisfy the constraint + t.toString(); // error, for the same reason as f1() +} + + +//// [genericUnboundedTypeParamAssignability.js] +"use strict"; +function f1(o) { + o.toString(); // error +} +function f2(o) { + o.toString(); // no error +} +function f3(o) { + o.toString(); // no error +} +function user(t) { + f1(t); + f2(t); // error in strict, unbounded T doesn't satisfy the constraint + f3(t); // error in strict, unbounded T doesn't satisfy the constraint + t.toString(); // error, for the same reason as f1() +} diff --git a/tests/baselines/reference/genericUnboundedTypeParamAssignability.symbols b/tests/baselines/reference/genericUnboundedTypeParamAssignability.symbols new file mode 100644 index 00000000000..b394adbbacb --- /dev/null +++ b/tests/baselines/reference/genericUnboundedTypeParamAssignability.symbols @@ -0,0 +1,58 @@ +=== tests/cases/compiler/genericUnboundedTypeParamAssignability.ts === +function f1(o: T) { +>f1 : Symbol(f1, Decl(genericUnboundedTypeParamAssignability.ts, 0, 0)) +>T : Symbol(T, Decl(genericUnboundedTypeParamAssignability.ts, 0, 12)) +>o : Symbol(o, Decl(genericUnboundedTypeParamAssignability.ts, 0, 15)) +>T : Symbol(T, Decl(genericUnboundedTypeParamAssignability.ts, 0, 12)) + + o.toString(); // error +>o : Symbol(o, Decl(genericUnboundedTypeParamAssignability.ts, 0, 15)) +} + +function f2(o: T) { +>f2 : Symbol(f2, Decl(genericUnboundedTypeParamAssignability.ts, 2, 1)) +>T : Symbol(T, Decl(genericUnboundedTypeParamAssignability.ts, 4, 12)) +>o : Symbol(o, Decl(genericUnboundedTypeParamAssignability.ts, 4, 26)) +>T : Symbol(T, Decl(genericUnboundedTypeParamAssignability.ts, 4, 12)) + + o.toString(); // no error +>o.toString : Symbol(Object.toString, Decl(lib.es5.d.ts, --, --)) +>o : Symbol(o, Decl(genericUnboundedTypeParamAssignability.ts, 4, 26)) +>toString : Symbol(Object.toString, Decl(lib.es5.d.ts, --, --)) +} + +function f3>(o: T) { +>f3 : Symbol(f3, Decl(genericUnboundedTypeParamAssignability.ts, 6, 1)) +>T : Symbol(T, Decl(genericUnboundedTypeParamAssignability.ts, 8, 12)) +>Record : Symbol(Record, Decl(lib.es5.d.ts, --, --)) +>o : Symbol(o, Decl(genericUnboundedTypeParamAssignability.ts, 8, 43)) +>T : Symbol(T, Decl(genericUnboundedTypeParamAssignability.ts, 8, 12)) + + o.toString(); // no error +>o.toString : Symbol(Object.toString, Decl(lib.es5.d.ts, --, --)) +>o : Symbol(o, Decl(genericUnboundedTypeParamAssignability.ts, 8, 43)) +>toString : Symbol(Object.toString, Decl(lib.es5.d.ts, --, --)) +} + +function user(t: T) { +>user : Symbol(user, Decl(genericUnboundedTypeParamAssignability.ts, 10, 1)) +>T : Symbol(T, Decl(genericUnboundedTypeParamAssignability.ts, 12, 14)) +>t : Symbol(t, Decl(genericUnboundedTypeParamAssignability.ts, 12, 17)) +>T : Symbol(T, Decl(genericUnboundedTypeParamAssignability.ts, 12, 14)) + + f1(t); +>f1 : Symbol(f1, Decl(genericUnboundedTypeParamAssignability.ts, 0, 0)) +>t : Symbol(t, Decl(genericUnboundedTypeParamAssignability.ts, 12, 17)) + + f2(t); // error in strict, unbounded T doesn't satisfy the constraint +>f2 : Symbol(f2, Decl(genericUnboundedTypeParamAssignability.ts, 2, 1)) +>t : Symbol(t, Decl(genericUnboundedTypeParamAssignability.ts, 12, 17)) + + f3(t); // error in strict, unbounded T doesn't satisfy the constraint +>f3 : Symbol(f3, Decl(genericUnboundedTypeParamAssignability.ts, 6, 1)) +>t : Symbol(t, Decl(genericUnboundedTypeParamAssignability.ts, 12, 17)) + + t.toString(); // error, for the same reason as f1() +>t : Symbol(t, Decl(genericUnboundedTypeParamAssignability.ts, 12, 17)) +} + diff --git a/tests/baselines/reference/genericUnboundedTypeParamAssignability.types b/tests/baselines/reference/genericUnboundedTypeParamAssignability.types new file mode 100644 index 00000000000..74136a19382 --- /dev/null +++ b/tests/baselines/reference/genericUnboundedTypeParamAssignability.types @@ -0,0 +1,60 @@ +=== tests/cases/compiler/genericUnboundedTypeParamAssignability.ts === +function f1(o: T) { +>f1 : (o: T) => void +>o : T + + o.toString(); // error +>o.toString() : any +>o.toString : any +>o : T +>toString : any +} + +function f2(o: T) { +>f2 : (o: T) => void +>o : T + + o.toString(); // no error +>o.toString() : string +>o.toString : () => string +>o : T +>toString : () => string +} + +function f3>(o: T) { +>f3 : >(o: T) => void +>o : T + + o.toString(); // no error +>o.toString() : string +>o.toString : () => string +>o : T +>toString : () => string +} + +function user(t: T) { +>user : (t: T) => void +>t : T + + f1(t); +>f1(t) : void +>f1 : (o: T) => void +>t : T + + f2(t); // error in strict, unbounded T doesn't satisfy the constraint +>f2(t) : void +>f2 : (o: T) => void +>t : T + + f3(t); // error in strict, unbounded T doesn't satisfy the constraint +>f3(t) : void +>f3 : >(o: T) => void +>t : T + + t.toString(); // error, for the same reason as f1() +>t.toString() : any +>t.toString : any +>t : T +>toString : any +} + diff --git a/tests/baselines/reference/importSpecifiers_js.errors.txt b/tests/baselines/reference/importSpecifiers_js.errors.txt new file mode 100644 index 00000000000..98e07951a2d --- /dev/null +++ b/tests/baselines/reference/importSpecifiers_js.errors.txt @@ -0,0 +1,11 @@ +tests/cases/conformance/externalModules/typeOnly/a.js(1,10): error TS8006: 'import...type' declarations can only be used in TypeScript files. + + +==== tests/cases/conformance/externalModules/typeOnly/a.ts (0 errors) ==== + export interface A {} + +==== tests/cases/conformance/externalModules/typeOnly/a.js (1 errors) ==== + import { type A } from "./a"; + ~~~~~~ +!!! error TS8006: 'import...type' declarations can only be used in TypeScript files. + \ No newline at end of file diff --git a/tests/baselines/reference/importSpecifiers_js.symbols b/tests/baselines/reference/importSpecifiers_js.symbols new file mode 100644 index 00000000000..c486fa6bb7a --- /dev/null +++ b/tests/baselines/reference/importSpecifiers_js.symbols @@ -0,0 +1,8 @@ +=== tests/cases/conformance/externalModules/typeOnly/a.ts === +export interface A {} +>A : Symbol(A, Decl(a.ts, 0, 0)) + +=== tests/cases/conformance/externalModules/typeOnly/a.js === +import { type A } from "./a"; +>A : Symbol(A, Decl(a.js, 0, 8)) + diff --git a/tests/baselines/reference/importSpecifiers_js.types b/tests/baselines/reference/importSpecifiers_js.types new file mode 100644 index 00000000000..b668b5e5fe2 --- /dev/null +++ b/tests/baselines/reference/importSpecifiers_js.types @@ -0,0 +1,7 @@ +=== tests/cases/conformance/externalModules/typeOnly/a.ts === +export interface A {} +No type information for this code. +No type information for this code.=== tests/cases/conformance/externalModules/typeOnly/a.js === +import { type A } from "./a"; +>A : any + diff --git a/tests/baselines/reference/isomorphicMappedTypeInference.js b/tests/baselines/reference/isomorphicMappedTypeInference.js index 778eae45426..04f6bfbff1e 100644 --- a/tests/baselines/reference/isomorphicMappedTypeInference.js +++ b/tests/baselines/reference/isomorphicMappedTypeInference.js @@ -23,7 +23,7 @@ function boxify(obj: T): Boxified { return result; } -function unboxify(obj: Boxified): T { +function unboxify(obj: Boxified): T { let result = {} as T; for (let k in obj) { result[k] = unbox(obj[k]); @@ -307,7 +307,7 @@ declare type Boxified = { declare function box(x: T): Box; declare function unbox(x: Box): T; declare function boxify(obj: T): Boxified; -declare function unboxify(obj: Boxified): T; +declare function unboxify(obj: Boxified): T; declare function assignBoxified(obj: Boxified, values: T): void; declare function f1(): void; declare function f2(): void; diff --git a/tests/baselines/reference/isomorphicMappedTypeInference.symbols b/tests/baselines/reference/isomorphicMappedTypeInference.symbols index 3192be13ff6..45d97005e37 100644 --- a/tests/baselines/reference/isomorphicMappedTypeInference.symbols +++ b/tests/baselines/reference/isomorphicMappedTypeInference.symbols @@ -75,10 +75,10 @@ function boxify(obj: T): Boxified { >result : Symbol(result, Decl(isomorphicMappedTypeInference.ts, 17, 7)) } -function unboxify(obj: Boxified): T { +function unboxify(obj: Boxified): T { >unboxify : Symbol(unboxify, Decl(isomorphicMappedTypeInference.ts, 22, 1)) >T : Symbol(T, Decl(isomorphicMappedTypeInference.ts, 24, 18)) ->obj : Symbol(obj, Decl(isomorphicMappedTypeInference.ts, 24, 21)) +>obj : Symbol(obj, Decl(isomorphicMappedTypeInference.ts, 24, 36)) >Boxified : Symbol(Boxified, Decl(isomorphicMappedTypeInference.ts, 2, 1)) >T : Symbol(T, Decl(isomorphicMappedTypeInference.ts, 24, 18)) >T : Symbol(T, Decl(isomorphicMappedTypeInference.ts, 24, 18)) @@ -89,13 +89,13 @@ function unboxify(obj: Boxified): T { for (let k in obj) { >k : Symbol(k, Decl(isomorphicMappedTypeInference.ts, 26, 12)) ->obj : Symbol(obj, Decl(isomorphicMappedTypeInference.ts, 24, 21)) +>obj : Symbol(obj, Decl(isomorphicMappedTypeInference.ts, 24, 36)) result[k] = unbox(obj[k]); >result : Symbol(result, Decl(isomorphicMappedTypeInference.ts, 25, 7)) >k : Symbol(k, Decl(isomorphicMappedTypeInference.ts, 26, 12)) >unbox : Symbol(unbox, Decl(isomorphicMappedTypeInference.ts, 10, 1)) ->obj : Symbol(obj, Decl(isomorphicMappedTypeInference.ts, 24, 21)) +>obj : Symbol(obj, Decl(isomorphicMappedTypeInference.ts, 24, 36)) >k : Symbol(k, Decl(isomorphicMappedTypeInference.ts, 26, 12)) } return result; diff --git a/tests/baselines/reference/isomorphicMappedTypeInference.types b/tests/baselines/reference/isomorphicMappedTypeInference.types index 608c5e79df2..800500764a5 100644 --- a/tests/baselines/reference/isomorphicMappedTypeInference.types +++ b/tests/baselines/reference/isomorphicMappedTypeInference.types @@ -60,8 +60,8 @@ function boxify(obj: T): Boxified { >result : Boxified } -function unboxify(obj: Boxified): T { ->unboxify : (obj: Boxified) => T +function unboxify(obj: Boxified): T { +>unboxify : (obj: Boxified) => T >obj : Boxified let result = {} as T; @@ -174,7 +174,7 @@ function f2() { let v = unboxify(b); >v : { a: number; b: string; c: boolean; } >unboxify(b) : { a: number; b: string; c: boolean; } ->unboxify : (obj: Boxified) => T +>unboxify : (obj: Boxified) => T >b : { a: Box; b: Box; c: Box; } let x: number = v.a; @@ -251,14 +251,14 @@ function f4() { >boxify(unboxify(b)) : Boxified<{ a: number; b: string; c: boolean; }> >boxify : (obj: T) => Boxified >unboxify(b) : { a: number; b: string; c: boolean; } ->unboxify : (obj: Boxified) => T +>unboxify : (obj: Boxified) => T >b : { a: Box; b: Box; c: Box; } b = unboxify(boxify(b)); >b = unboxify(boxify(b)) : { a: Box; b: Box; c: Box; } >b : { a: Box; b: Box; c: Box; } >unboxify(boxify(b)) : { a: Box; b: Box; c: Box; } ->unboxify : (obj: Boxified) => T +>unboxify : (obj: Boxified) => T >boxify(b) : Boxified<{ a: Box; b: Box; c: Box; }> >boxify : (obj: T) => Boxified >b : { a: Box; b: Box; c: Box; } @@ -304,7 +304,7 @@ function f5(s: string) { let v = unboxify(b); >v : { a: string | number | boolean; b: string | number | boolean; c: string | number | boolean; } >unboxify(b) : { a: string | number | boolean; b: string | number | boolean; c: string | number | boolean; } ->unboxify : (obj: Boxified) => T +>unboxify : (obj: Boxified) => T >b : { a: Box | Box | Box; b: Box | Box | Box; c: Box | Box | Box; } let x: string | number | boolean = v.a; @@ -355,7 +355,7 @@ function f6(s: string) { let v = unboxify(b); >v : { [x: string]: any; } >unboxify(b) : { [x: string]: any; } ->unboxify : (obj: Boxified) => T +>unboxify : (obj: Boxified) => T >b : { [x: string]: Box | Box | Box; } let x: string | number | boolean = v[s]; diff --git a/tests/baselines/reference/jsDocFunctionSignatures6.baseline b/tests/baselines/reference/jsDocFunctionSignatures6.baseline index 7c147a6ec2c..2d5e8aebc83 100644 --- a/tests/baselines/reference/jsDocFunctionSignatures6.baseline +++ b/tests/baselines/reference/jsDocFunctionSignatures6.baseline @@ -52,7 +52,7 @@ "name": "p1", "documentation": [ { - "text": "A string param", + "text": "- A string param", "kind": "text" } ], @@ -81,7 +81,7 @@ "name": "p2", "documentation": [ { - "text": "An optional param", + "text": "- An optional param", "kind": "text" } ], @@ -110,7 +110,7 @@ "name": "p3", "documentation": [ { - "text": "Another optional param", + "text": "- Another optional param", "kind": "text" } ], @@ -143,7 +143,7 @@ "name": "p4", "documentation": [ { - "text": "An optional param with a default value", + "text": "- An optional param with a default value", "kind": "text" } ], @@ -187,7 +187,7 @@ "kind": "space" }, { - "text": "A string param", + "text": "- A string param", "kind": "text" } ] @@ -204,7 +204,7 @@ "kind": "space" }, { - "text": "An optional param", + "text": "- An optional param", "kind": "text" } ] @@ -221,7 +221,7 @@ "kind": "space" }, { - "text": "Another optional param", + "text": "- Another optional param", "kind": "text" } ] @@ -238,7 +238,7 @@ "kind": "space" }, { - "text": "An optional param with a default value", + "text": "- An optional param with a default value", "kind": "text" } ] @@ -308,7 +308,7 @@ "name": "p1", "documentation": [ { - "text": "A string param", + "text": "- A string param", "kind": "text" } ], @@ -337,7 +337,7 @@ "name": "p2", "documentation": [ { - "text": "An optional param", + "text": "- An optional param", "kind": "text" } ], @@ -366,7 +366,7 @@ "name": "p3", "documentation": [ { - "text": "Another optional param", + "text": "- Another optional param", "kind": "text" } ], @@ -399,7 +399,7 @@ "name": "p4", "documentation": [ { - "text": "An optional param with a default value", + "text": "- An optional param with a default value", "kind": "text" } ], @@ -443,7 +443,7 @@ "kind": "space" }, { - "text": "A string param", + "text": "- A string param", "kind": "text" } ] @@ -460,7 +460,7 @@ "kind": "space" }, { - "text": "An optional param", + "text": "- An optional param", "kind": "text" } ] @@ -477,7 +477,7 @@ "kind": "space" }, { - "text": "Another optional param", + "text": "- Another optional param", "kind": "text" } ] @@ -494,7 +494,7 @@ "kind": "space" }, { - "text": "An optional param with a default value", + "text": "- An optional param with a default value", "kind": "text" } ] @@ -564,7 +564,7 @@ "name": "p1", "documentation": [ { - "text": "A string param", + "text": "- A string param", "kind": "text" } ], @@ -593,7 +593,7 @@ "name": "p2", "documentation": [ { - "text": "An optional param", + "text": "- An optional param", "kind": "text" } ], @@ -622,7 +622,7 @@ "name": "p3", "documentation": [ { - "text": "Another optional param", + "text": "- Another optional param", "kind": "text" } ], @@ -655,7 +655,7 @@ "name": "p4", "documentation": [ { - "text": "An optional param with a default value", + "text": "- An optional param with a default value", "kind": "text" } ], @@ -699,7 +699,7 @@ "kind": "space" }, { - "text": "A string param", + "text": "- A string param", "kind": "text" } ] @@ -716,7 +716,7 @@ "kind": "space" }, { - "text": "An optional param", + "text": "- An optional param", "kind": "text" } ] @@ -733,7 +733,7 @@ "kind": "space" }, { - "text": "Another optional param", + "text": "- Another optional param", "kind": "text" } ] @@ -750,7 +750,7 @@ "kind": "space" }, { - "text": "An optional param with a default value", + "text": "- An optional param with a default value", "kind": "text" } ] @@ -820,7 +820,7 @@ "name": "p1", "documentation": [ { - "text": "A string param", + "text": "- A string param", "kind": "text" } ], @@ -849,7 +849,7 @@ "name": "p2", "documentation": [ { - "text": "An optional param", + "text": "- An optional param", "kind": "text" } ], @@ -878,7 +878,7 @@ "name": "p3", "documentation": [ { - "text": "Another optional param", + "text": "- Another optional param", "kind": "text" } ], @@ -911,7 +911,7 @@ "name": "p4", "documentation": [ { - "text": "An optional param with a default value", + "text": "- An optional param with a default value", "kind": "text" } ], @@ -955,7 +955,7 @@ "kind": "space" }, { - "text": "A string param", + "text": "- A string param", "kind": "text" } ] @@ -972,7 +972,7 @@ "kind": "space" }, { - "text": "An optional param", + "text": "- An optional param", "kind": "text" } ] @@ -989,7 +989,7 @@ "kind": "space" }, { - "text": "Another optional param", + "text": "- Another optional param", "kind": "text" } ] @@ -1006,7 +1006,7 @@ "kind": "space" }, { - "text": "An optional param with a default value", + "text": "- An optional param with a default value", "kind": "text" } ] diff --git a/tests/baselines/reference/keyofAndIndexedAccess.errors.txt b/tests/baselines/reference/keyofAndIndexedAccess.errors.txt new file mode 100644 index 00000000000..f5c436bbf1d --- /dev/null +++ b/tests/baselines/reference/keyofAndIndexedAccess.errors.txt @@ -0,0 +1,709 @@ +tests/cases/conformance/types/keyof/keyofAndIndexedAccess.ts(316,5): error TS2322: Type 'T' is not assignable to type '{}'. +tests/cases/conformance/types/keyof/keyofAndIndexedAccess.ts(317,5): error TS2322: Type 'T[keyof T]' is not assignable to type '{}'. + Type 'T[string] | T[number] | T[symbol]' is not assignable to type '{}'. + Type 'T[string]' is not assignable to type '{}'. +tests/cases/conformance/types/keyof/keyofAndIndexedAccess.ts(318,5): error TS2322: Type 'T[K]' is not assignable to type '{}'. + Type 'T[keyof T]' is not assignable to type '{}'. +tests/cases/conformance/types/keyof/keyofAndIndexedAccess.ts(323,5): error TS2322: Type 'T' is not assignable to type '{} | null | undefined'. +tests/cases/conformance/types/keyof/keyofAndIndexedAccess.ts(324,5): error TS2322: Type 'T[keyof T]' is not assignable to type '{} | null | undefined'. + Type 'T[string] | T[number] | T[symbol]' is not assignable to type '{} | null | undefined'. + Type 'T[string]' is not assignable to type '{} | null | undefined'. +tests/cases/conformance/types/keyof/keyofAndIndexedAccess.ts(325,5): error TS2322: Type 'T[K]' is not assignable to type '{} | null | undefined'. + Type 'T[keyof T]' is not assignable to type '{} | null | undefined'. +tests/cases/conformance/types/keyof/keyofAndIndexedAccess.ts(611,33): error TS2345: Argument of type 'T[K]' is not assignable to parameter of type '{} | null | undefined'. + Type 'T[keyof T]' is not assignable to type '{} | null | undefined'. + Type 'T[string] | T[number] | T[symbol]' is not assignable to type '{} | null | undefined'. + Type 'T[string]' is not assignable to type '{} | null | undefined'. +tests/cases/conformance/types/keyof/keyofAndIndexedAccess.ts(619,13): error TS2322: Type 'T[keyof T]' is not assignable to type '{} | null | undefined'. + Type 'T[string] | T[number] | T[symbol]' is not assignable to type '{} | null | undefined'. + Type 'T[string]' is not assignable to type '{} | null | undefined'. + + +==== tests/cases/conformance/types/keyof/keyofAndIndexedAccess.ts (8 errors) ==== + class Shape { + name: string; + width: number; + height: number; + visible: boolean; + } + + class TaggedShape extends Shape { + tag: string; + } + + class Item { + name: string; + price: number; + } + + class Options { + visible: "yes" | "no"; + } + + type Dictionary = { [x: string]: T }; + type NumericallyIndexed = { [x: number]: T }; + + const enum E { A, B, C } + + type K00 = keyof any; // string + type K01 = keyof string; // "toString" | "charAt" | ... + type K02 = keyof number; // "toString" | "toFixed" | "toExponential" | ... + type K03 = keyof boolean; // "valueOf" + type K04 = keyof void; // never + type K05 = keyof undefined; // never + type K06 = keyof null; // never + type K07 = keyof never; // string | number | symbol + type K08 = keyof unknown; // never + + type K10 = keyof Shape; // "name" | "width" | "height" | "visible" + type K11 = keyof Shape[]; // "length" | "toString" | ... + type K12 = keyof Dictionary; // string + type K13 = keyof {}; // never + type K14 = keyof Object; // "constructor" | "toString" | ... + type K15 = keyof E; // "toString" | "toFixed" | "toExponential" | ... + type K16 = keyof [string, number]; // "0" | "1" | "length" | "toString" | ... + type K17 = keyof (Shape | Item); // "name" + type K18 = keyof (Shape & Item); // "name" | "width" | "height" | "visible" | "price" + type K19 = keyof NumericallyIndexed // never + + type KeyOf = keyof T; + + type K20 = KeyOf; // "name" | "width" | "height" | "visible" + type K21 = KeyOf>; // string + + type NAME = "name"; + type WIDTH_OR_HEIGHT = "width" | "height"; + + type Q10 = Shape["name"]; // string + type Q11 = Shape["width" | "height"]; // number + type Q12 = Shape["name" | "visible"]; // string | boolean + + type Q20 = Shape[NAME]; // string + type Q21 = Shape[WIDTH_OR_HEIGHT]; // number + + type Q30 = [string, number][0]; // string + type Q31 = [string, number][1]; // number + type Q32 = [string, number][number]; // string | number + type Q33 = [string, number][E.A]; // string + type Q34 = [string, number][E.B]; // number + type Q35 = [string, number]["0"]; // string + type Q36 = [string, number]["1"]; // string + + type Q40 = (Shape | Options)["visible"]; // boolean | "yes" | "no" + type Q41 = (Shape & Options)["visible"]; // true & "yes" | true & "no" | false & "yes" | false & "no" + + type Q50 = Dictionary["howdy"]; // Shape + type Q51 = Dictionary[123]; // Shape + type Q52 = Dictionary[E.B]; // Shape + + declare let cond: boolean; + + function getProperty(obj: T, key: K) { + return obj[key]; + } + + function setProperty(obj: T, key: K, value: T[K]) { + obj[key] = value; + } + + function f10(shape: Shape) { + let name = getProperty(shape, "name"); // string + let widthOrHeight = getProperty(shape, cond ? "width" : "height"); // number + let nameOrVisible = getProperty(shape, cond ? "name" : "visible"); // string | boolean + setProperty(shape, "name", "rectangle"); + setProperty(shape, cond ? "width" : "height", 10); + setProperty(shape, cond ? "name" : "visible", true); // Technically not safe + } + + function f11(a: Shape[]) { + let len = getProperty(a, "length"); // number + setProperty(a, "length", len); + } + + function f12(t: [Shape, boolean]) { + let len = getProperty(t, "length"); + let s2 = getProperty(t, "0"); // Shape + let b2 = getProperty(t, "1"); // boolean + } + + function f13(foo: any, bar: any) { + let x = getProperty(foo, "x"); // any + let y = getProperty(foo, "100"); // any + let z = getProperty(foo, bar); // any + } + + class Component { + props: PropType; + getProperty(key: K) { + return this.props[key]; + } + setProperty(key: K, value: PropType[K]) { + this.props[key] = value; + } + } + + function f20(component: Component) { + let name = component.getProperty("name"); // string + let widthOrHeight = component.getProperty(cond ? "width" : "height"); // number + let nameOrVisible = component.getProperty(cond ? "name" : "visible"); // string | boolean + component.setProperty("name", "rectangle"); + component.setProperty(cond ? "width" : "height", 10) + component.setProperty(cond ? "name" : "visible", true); // Technically not safe + } + + function pluck(array: T[], key: K) { + return array.map(x => x[key]); + } + + function f30(shapes: Shape[]) { + let names = pluck(shapes, "name"); // string[] + let widths = pluck(shapes, "width"); // number[] + let nameOrVisibles = pluck(shapes, cond ? "name" : "visible"); // (string | boolean)[] + } + + function f31(key: K) { + const shape: Shape = { name: "foo", width: 5, height: 10, visible: true }; + return shape[key]; // Shape[K] + } + + function f32(key: K) { + const shape: Shape = { name: "foo", width: 5, height: 10, visible: true }; + return shape[key]; // Shape[K] + } + + function f33(shape: S, key: K) { + let name = getProperty(shape, "name"); + let prop = getProperty(shape, key); + return prop; + } + + function f34(ts: TaggedShape) { + let tag1 = f33(ts, "tag"); + let tag2 = getProperty(ts, "tag"); + } + + class C { + public x: string; + protected y: string; + private z: string; + } + + // Indexed access expressions have always permitted access to private and protected members. + // For consistency we also permit such access in indexed access types. + function f40(c: C) { + type X = C["x"]; + type Y = C["y"]; + type Z = C["z"]; + let x: X = c["x"]; + let y: Y = c["y"]; + let z: Z = c["z"]; + } + + function f50(k: keyof T, s: string) { + const x1 = s as keyof T; + const x2 = k as string; + } + + function f51(k: K, s: string) { + const x1 = s as keyof T; + const x2 = k as string; + } + + function f52(obj: { [x: string]: boolean }, k: Exclude, s: string, n: number) { + const x1 = obj[s]; + const x2 = obj[n]; + const x3 = obj[k]; + } + + function f53>(obj: { [x: string]: boolean }, k: K, s: string, n: number) { + const x1 = obj[s]; + const x2 = obj[n]; + const x3 = obj[k]; + } + + function f54(obj: T, key: keyof T) { + for (let s in obj[key]) { + } + const b = "foo" in obj[key]; + } + + function f55(obj: T, key: K) { + for (let s in obj[key]) { + } + const b = "foo" in obj[key]; + } + + function f60(source: T, target: T) { + for (let k in source) { + target[k] = source[k]; + } + } + + function f70(func: (k1: keyof (T | U), k2: keyof (T & U)) => void) { + func<{ a: any, b: any }, { a: any, c: any }>('a', 'a'); + func<{ a: any, b: any }, { a: any, c: any }>('a', 'b'); + func<{ a: any, b: any }, { a: any, c: any }>('a', 'c'); + } + + function f71(func: (x: T, y: U) => Partial) { + let x = func({ a: 1, b: "hello" }, { c: true }); + x.a; // number | undefined + x.b; // string | undefined + x.c; // boolean | undefined + } + + function f72(func: (x: T, y: U, k: K) => (T & U)[K]) { + let a = func({ a: 1, b: "hello" }, { c: true }, 'a'); // number + let b = func({ a: 1, b: "hello" }, { c: true }, 'b'); // string + let c = func({ a: 1, b: "hello" }, { c: true }, 'c'); // boolean + } + + function f73(func: (x: T, y: U, k: K) => (T & U)[K]) { + let a = func({ a: 1, b: "hello" }, { c: true }, 'a'); // number + let b = func({ a: 1, b: "hello" }, { c: true }, 'b'); // string + let c = func({ a: 1, b: "hello" }, { c: true }, 'c'); // boolean + } + + function f74(func: (x: T, y: U, k: K) => (T | U)[K]) { + let a = func({ a: 1, b: "hello" }, { a: 2, b: true }, 'a'); // number + let b = func({ a: 1, b: "hello" }, { a: 2, b: true }, 'b'); // string | boolean + } + + function f80(obj: T) { + let a1 = obj.a; // { x: any } + let a2 = obj['a']; // { x: any } + let a3 = obj['a'] as T['a']; // T["a"] + let x1 = obj.a.x; // any + let x2 = obj['a']['x']; // any + let x3 = obj['a']['x'] as T['a']['x']; // T["a"]["x"] + } + + function f81(obj: T) { + return obj['a']['x'] as T['a']['x']; + } + + function f82() { + let x1 = f81({ a: { x: "hello" } }); // string + let x2 = f81({ a: { x: 42 } }); // number + } + + function f83(obj: T, key: K) { + return obj[key]['x'] as T[K]['x']; + } + + function f84() { + let x1 = f83({ foo: { x: "hello" } }, "foo"); // string + let x2 = f83({ bar: { x: 42 } }, "bar"); // number + } + + class C1 { + x: number; + get(key: K) { + return this[key]; + } + set(key: K, value: this[K]) { + this[key] = value; + } + foo() { + let x1 = this.x; // number + let x2 = this["x"]; // number + let x3 = this.get("x"); // this["x"] + let x4 = getProperty(this, "x"); // this["x"] + this.x = 42; + this["x"] = 42; + this.set("x", 42); + setProperty(this, "x", 42); + } + } + + type S2 = { + a: string; + b: string; + }; + + function f90(x1: S2[keyof S2], x2: T[keyof S2], x3: S2[K]) { + x1 = x2; + x1 = x3; + x2 = x1; + x2 = x3; + x3 = x1; + x3 = x2; + x1.length; + x2.length; + x3.length; + } + + function f91(x: T, y: T[keyof T], z: T[K]) { + let a: {}; + a = x; + ~ +!!! error TS2322: Type 'T' is not assignable to type '{}'. +!!! related TS2208 tests/cases/conformance/types/keyof/keyofAndIndexedAccess.ts:314:14: This type parameter probably needs an `extends object` constraint. + a = y; + ~ +!!! error TS2322: Type 'T[keyof T]' is not assignable to type '{}'. +!!! error TS2322: Type 'T[string] | T[number] | T[symbol]' is not assignable to type '{}'. +!!! error TS2322: Type 'T[string]' is not assignable to type '{}'. + a = z; + ~ +!!! error TS2322: Type 'T[K]' is not assignable to type '{}'. +!!! error TS2322: Type 'T[keyof T]' is not assignable to type '{}'. + } + + function f92(x: T, y: T[keyof T], z: T[K]) { + let a: {} | null | undefined; + a = x; + ~ +!!! error TS2322: Type 'T' is not assignable to type '{} | null | undefined'. +!!! related TS2208 tests/cases/conformance/types/keyof/keyofAndIndexedAccess.ts:321:14: This type parameter probably needs an `extends object` constraint. + a = y; + ~ +!!! error TS2322: Type 'T[keyof T]' is not assignable to type '{} | null | undefined'. +!!! error TS2322: Type 'T[string] | T[number] | T[symbol]' is not assignable to type '{} | null | undefined'. +!!! error TS2322: Type 'T[string]' is not assignable to type '{} | null | undefined'. + a = z; + ~ +!!! error TS2322: Type 'T[K]' is not assignable to type '{} | null | undefined'. +!!! error TS2322: Type 'T[keyof T]' is not assignable to type '{} | null | undefined'. + } + + // Repros from #12011 + + class Base { + get(prop: K) { + return this[prop]; + } + set(prop: K, value: this[K]) { + this[prop] = value; + } + } + + class Person extends Base { + parts: number; + constructor(parts: number) { + super(); + this.set("parts", parts); + } + getParts() { + return this.get("parts") + } + } + + class OtherPerson { + parts: number; + constructor(parts: number) { + setProperty(this, "parts", parts); + } + getParts() { + return getProperty(this, "parts") + } + } + + // Modified repro from #12544 + + function path(obj: T, key1: K1): T[K1]; + function path(obj: T, key1: K1, key2: K2): T[K1][K2]; + function path(obj: T, key1: K1, key2: K2, key3: K3): T[K1][K2][K3]; + function path(obj: any, ...keys: (string | number)[]): any; + function path(obj: any, ...keys: (string | number)[]): any { + let result = obj; + for (let k of keys) { + result = result[k]; + } + return result; + } + + type Thing = { + a: { x: number, y: string }, + b: boolean + }; + + + function f1(thing: Thing) { + let x1 = path(thing, 'a'); // { x: number, y: string } + let x2 = path(thing, 'a', 'y'); // string + let x3 = path(thing, 'b'); // boolean + let x4 = path(thing, ...['a', 'x']); // any + } + + // Repro from comment in #12114 + + const assignTo2 = (object: T, key1: K1, key2: K2) => + (value: T[K1][K2]) => object[key1][key2] = value; + + // Modified repro from #12573 + + declare function one(handler: (t: T) => void): T + var empty = one(() => {}) // inferred as {}, expected + + type Handlers = { [K in keyof T]: (t: T[K]) => void } + declare function on(handlerHash: Handlers): T + var hashOfEmpty1 = on({ test: () => {} }); // {} + var hashOfEmpty2 = on({ test: (x: boolean) => {} }); // { test: boolean } + + // Repro from #12624 + + interface Options1 { + data?: Data + computed?: Computed; + } + + declare class Component1 { + constructor(options: Options1); + get(key: K): (Data & Computed)[K]; + } + + let c1 = new Component1({ + data: { + hello: "" + } + }); + + c1.get("hello"); + + // Repro from #12625 + + interface Options2 { + data?: Data + computed?: Computed; + } + + declare class Component2 { + constructor(options: Options2); + get(key: K): (Data & Computed)[K]; + } + + // Repro from #12641 + + interface R { + p: number; + } + + function f(p: K) { + let a: any; + a[p].add; // any + } + + // Repro from #12651 + + type MethodDescriptor = { + name: string; + args: any[]; + returnValue: any; + } + + declare function dispatchMethod(name: M['name'], args: M['args']): M['returnValue']; + + type SomeMethodDescriptor = { + name: "someMethod"; + args: [string, number]; + returnValue: string[]; + } + + let result = dispatchMethod("someMethod", ["hello", 35]); + + // Repro from #13073 + + type KeyTypes = "a" | "b" + let MyThingy: { [key in KeyTypes]: string[] }; + + function addToMyThingy(key: S) { + MyThingy[key].push("a"); + } + + // Repro from #13102 + + type Handler = { + onChange: (name: keyof T) => void; + }; + + function onChangeGenericFunction(handler: Handler) { + handler.onChange('preset') + } + + // Repro from #13285 + + function updateIds, K extends string>( + obj: T, + idFields: K[], + idMapping: Partial> + ): Record { + for (const idField of idFields) { + const newId: T[K] | undefined = idMapping[obj[idField]]; + if (newId) { + obj[idField] = newId; + } + } + return obj; + } + + // Repro from #13285 + + function updateIds2( + obj: T, + key: K, + stringMap: { [oldId: string]: string } + ) { + var x = obj[key]; + stringMap[x]; // Should be OK. + } + + // Repro from #13514 + + declare function head>(list: T): T[0]; + + // Repro from #13604 + + class A { + props: T & { foo: string }; + } + + class B extends A<{ x: number}> { + f(p: this["props"]) { + p.x; + } + } + + // Repro from #13749 + + class Form { + private childFormFactories: {[K in keyof T]: (v: T[K]) => Form} + + public set(prop: K, value: T[K]) { + this.childFormFactories[prop](value) + } + } + + // Repro from #13787 + + class SampleClass

{ + public props: Readonly

; + constructor(props: P) { + this.props = Object.freeze(props); + } + } + + interface Foo { + foo: string; + } + + declare function merge(obj1: T, obj2: U): T & U; + + class AnotherSampleClass extends SampleClass { + constructor(props: T) { + const foo: Foo = { foo: "bar" }; + super(merge(props, foo)); + } + + public brokenMethod() { + this.props.foo.concat; + } + } + new AnotherSampleClass({}); + + // Positive repro from #17166 + function f3>(t: T, k: K, tk: T[K]): void { + for (let key in t) { + key = k // ok, K ==> keyof T + t[key] = tk; // ok, T[K] ==> T[keyof T] + } + } + + // # 21185 + type Predicates = { + [T in keyof TaggedRecord]: (variant: TaggedRecord[keyof TaggedRecord]) => variant is TaggedRecord[T] + } + + // Repros from #23592 + + type Example = { [K in keyof T]: T[K]["prop"] }; + type Result = Example<{ a: { prop: string }; b: { prop: number } }>; + + type Helper2 = { [K in keyof T]: Extract }; + type Example2 = { [K in keyof Helper2]: Helper2[K]["prop"] }; + type Result2 = Example2<{ 1: { prop: string }; 2: { prop: number } }>; + + // Repro from #23618 + + type DBBoolTable = { [k in K]: 0 | 1 } + enum Flag { + FLAG_1 = "flag_1", + FLAG_2 = "flag_2" + } + + type SimpleDBRecord = { staticField: number } & DBBoolTable + function getFlagsFromSimpleRecord(record: SimpleDBRecord, flags: Flag[]) { + return record[flags[0]]; + } + + type DynamicDBRecord = ({ dynamicField: number } | { dynamicField: string }) & DBBoolTable + function getFlagsFromDynamicRecord(record: DynamicDBRecord, flags: Flag[]) { + return record[flags[0]]; + } + + // Repro from #21368 + + interface I { + foo: string; + } + + declare function take(p: T): void; + + function fn(o: T, k: K) { + take<{} | null | undefined>(o[k]); + ~~~~ +!!! error TS2345: Argument of type 'T[K]' is not assignable to parameter of type '{} | null | undefined'. +!!! error TS2345: Type 'T[keyof T]' is not assignable to type '{} | null | undefined'. +!!! error TS2345: Type 'T[string] | T[number] | T[symbol]' is not assignable to type '{} | null | undefined'. +!!! error TS2345: Type 'T[string]' is not assignable to type '{} | null | undefined'. + take(o[k]); + } + + // Repro from #23133 + + class Unbounded { + foo(x: T[keyof T]) { + let y: {} | undefined | null = x; + ~ +!!! error TS2322: Type 'T[keyof T]' is not assignable to type '{} | null | undefined'. +!!! error TS2322: Type 'T[string] | T[number] | T[symbol]' is not assignable to type '{} | null | undefined'. +!!! error TS2322: Type 'T[string]' is not assignable to type '{} | null | undefined'. + } + } + + // Repro from #23940 + + interface I7 { + x: any; + } + type Foo7 = T; + declare function f7(type: K): Foo7; + + // Repro from #21770 + + type Dict = { [key in T]: number }; + type DictDict = { [key in V]: Dict }; + + function ff1(dd: DictDict, k1: V, k2: T): number { + return dd[k1][k2]; + } + + function ff2(dd: DictDict, k1: V, k2: T): number { + const d: Dict = dd[k1]; + return d[k2]; + } + + // Repro from #26409 + + const cf1 = (t: T, k: K) => + { + const s: string = t[k]; + t.cool; + }; + + const cf2 = (t: T, k: K) => + { + const s: string = t[k]; + t.cool; + }; + \ No newline at end of file diff --git a/tests/baselines/reference/limitDeepInstantiations.errors.txt b/tests/baselines/reference/limitDeepInstantiations.errors.txt index 2cf5aade7fd..21b5f53b04e 100644 --- a/tests/baselines/reference/limitDeepInstantiations.errors.txt +++ b/tests/baselines/reference/limitDeepInstantiations.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/limitDeepInstantiations.ts(3,35): error TS2502: '"true"' is referenced directly or indirectly in its own type annotation. +tests/cases/compiler/limitDeepInstantiations.ts(4,9): error TS2589: Type instantiation is excessively deep and possibly infinite. tests/cases/compiler/limitDeepInstantiations.ts(5,13): error TS2344: Type '"false"' does not satisfy the constraint '"true"'. @@ -6,9 +6,9 @@ tests/cases/compiler/limitDeepInstantiations.ts(5,13): error TS2344: Type '"fals // Repro from #14837 type Foo = { "true": Foo> }[T]; - ~~~~~~ -!!! error TS2502: '"true"' is referenced directly or indirectly in its own type annotation. let f1: Foo<"true", {}>; + ~~~~~~~~~~~~~~~ +!!! error TS2589: Type instantiation is excessively deep and possibly infinite. let f2: Foo<"false", {}>; ~~~~~~~ !!! error TS2344: Type '"false"' does not satisfy the constraint '"true"'. diff --git a/tests/baselines/reference/mappedTypesAndObjects.errors.txt b/tests/baselines/reference/mappedTypesAndObjects.errors.txt new file mode 100644 index 00000000000..c32fc58b370 --- /dev/null +++ b/tests/baselines/reference/mappedTypesAndObjects.errors.txt @@ -0,0 +1,54 @@ +tests/cases/conformance/types/mapped/mappedTypesAndObjects.ts(25,11): error TS2430: Interface 'E1' incorrectly extends interface 'Base'. + Types of property 'foo' are incompatible. + Type 'T' is not assignable to type '{ [key: string]: any; }'. + + +==== tests/cases/conformance/types/mapped/mappedTypesAndObjects.ts (1 errors) ==== + function f1(x: Partial, y: Readonly) { + let obj: {}; + obj = x; + obj = y; + } + + function f2(x: Partial, y: Readonly) { + let obj: { [x: string]: any }; + obj = x; + obj = y; + } + + function f3(x: Partial) { + x = {}; + } + + // Repro from #12900 + + interface Base { + foo: { [key: string]: any }; + bar: any; + baz: any; + } + + interface E1 extends Base { + ~~ +!!! error TS2430: Interface 'E1' incorrectly extends interface 'Base'. +!!! error TS2430: Types of property 'foo' are incompatible. +!!! error TS2430: Type 'T' is not assignable to type '{ [key: string]: any; }'. +!!! related TS2208 tests/cases/conformance/types/mapped/mappedTypesAndObjects.ts:25:14: This type parameter probably needs an `extends object` constraint. + foo: T; + } + + interface Something { name: string, value: string }; + interface E2 extends Base { + foo: Partial; // or other mapped type + } + + interface E3 extends Base { + foo: Partial; // or other mapped type + } + + // Repro from #13747 + + class Form { + private values: {[P in keyof T]?: T[P]} = {} + } + \ No newline at end of file diff --git a/tests/baselines/reference/noParameterReassignmentIIFEAnnotated.errors.txt b/tests/baselines/reference/noParameterReassignmentIIFEAnnotated.errors.txt new file mode 100644 index 00000000000..a3d7905a774 --- /dev/null +++ b/tests/baselines/reference/noParameterReassignmentIIFEAnnotated.errors.txt @@ -0,0 +1,15 @@ +tests/cases/compiler/index.js(3,28): error TS8029: JSDoc '@param' tag has name 'rest', but there is no parameter with that name. It would match 'arguments' if it had an array type. + + +==== tests/cases/compiler/index.js (1 errors) ==== + self.importScripts = (function (importScripts) { + /** + * @param {...unknown} rest + ~~~~ +!!! error TS8029: JSDoc '@param' tag has name 'rest', but there is no parameter with that name. It would match 'arguments' if it had an array type. + */ + return function () { + return importScripts.apply(this, arguments); + }; + })(importScripts); + \ No newline at end of file diff --git a/tests/baselines/reference/noParameterReassignmentIIFEAnnotated.symbols b/tests/baselines/reference/noParameterReassignmentIIFEAnnotated.symbols new file mode 100644 index 00000000000..f12c4e640aa --- /dev/null +++ b/tests/baselines/reference/noParameterReassignmentIIFEAnnotated.symbols @@ -0,0 +1,21 @@ +=== tests/cases/compiler/index.js === +self.importScripts = (function (importScripts) { +>self.importScripts : Symbol(importScripts, Decl(lib.webworker.importscripts.d.ts, --, --)) +>self : Symbol(self, Decl(lib.dom.d.ts, --, --), Decl(index.js, 0, 0)) +>importScripts : Symbol(importScripts, Decl(lib.webworker.importscripts.d.ts, --, --)) +>importScripts : Symbol(importScripts, Decl(index.js, 0, 32)) + + /** + * @param {...unknown} rest + */ + return function () { + return importScripts.apply(this, arguments); +>importScripts.apply : Symbol(Function.apply, Decl(lib.es5.d.ts, --, --)) +>importScripts : Symbol(importScripts, Decl(index.js, 0, 32)) +>apply : Symbol(Function.apply, Decl(lib.es5.d.ts, --, --)) +>arguments : Symbol(arguments) + + }; +})(importScripts); +>importScripts : Symbol(importScripts, Decl(lib.webworker.importscripts.d.ts, --, --)) + diff --git a/tests/baselines/reference/noParameterReassignmentIIFEAnnotated.types b/tests/baselines/reference/noParameterReassignmentIIFEAnnotated.types new file mode 100644 index 00000000000..ce2101e1c1c --- /dev/null +++ b/tests/baselines/reference/noParameterReassignmentIIFEAnnotated.types @@ -0,0 +1,29 @@ +=== tests/cases/compiler/index.js === +self.importScripts = (function (importScripts) { +>self.importScripts = (function (importScripts) { /** * @param {...unknown} rest */ return function () { return importScripts.apply(this, arguments); };})(importScripts) : (...args: unknown[]) => any +>self.importScripts : (...urls: string[]) => void +>self : Window & typeof globalThis +>importScripts : (...urls: string[]) => void +>(function (importScripts) { /** * @param {...unknown} rest */ return function () { return importScripts.apply(this, arguments); };})(importScripts) : (...args: unknown[]) => any +>(function (importScripts) { /** * @param {...unknown} rest */ return function () { return importScripts.apply(this, arguments); };}) : (importScripts: (...urls: string[]) => void) => (...args: unknown[]) => any +>function (importScripts) { /** * @param {...unknown} rest */ return function () { return importScripts.apply(this, arguments); };} : (importScripts: (...urls: string[]) => void) => (...args: unknown[]) => any +>importScripts : (...urls: string[]) => void + + /** + * @param {...unknown} rest + */ + return function () { +>function () { return importScripts.apply(this, arguments); } : (...args: unknown[]) => any + + return importScripts.apply(this, arguments); +>importScripts.apply(this, arguments) : any +>importScripts.apply : (this: Function, thisArg: any, argArray?: any) => any +>importScripts : (...urls: string[]) => void +>apply : (this: Function, thisArg: any, argArray?: any) => any +>this : any +>arguments : IArguments + + }; +})(importScripts); +>importScripts : (...urls: string[]) => void + diff --git a/tests/baselines/reference/noParameterReassignmentJSIIFE.symbols b/tests/baselines/reference/noParameterReassignmentJSIIFE.symbols new file mode 100644 index 00000000000..339cdfda0e5 --- /dev/null +++ b/tests/baselines/reference/noParameterReassignmentJSIIFE.symbols @@ -0,0 +1,18 @@ +=== tests/cases/compiler/index.js === +self.importScripts = (function (importScripts) { +>self.importScripts : Symbol(importScripts, Decl(lib.webworker.importscripts.d.ts, --, --)) +>self : Symbol(self, Decl(lib.dom.d.ts, --, --), Decl(index.js, 0, 0)) +>importScripts : Symbol(importScripts, Decl(lib.webworker.importscripts.d.ts, --, --)) +>importScripts : Symbol(importScripts, Decl(index.js, 0, 32)) + + return function () { + return importScripts.apply(this, arguments); +>importScripts.apply : Symbol(Function.apply, Decl(lib.es5.d.ts, --, --)) +>importScripts : Symbol(importScripts, Decl(index.js, 0, 32)) +>apply : Symbol(Function.apply, Decl(lib.es5.d.ts, --, --)) +>arguments : Symbol(arguments) + + }; +})(importScripts); +>importScripts : Symbol(importScripts, Decl(lib.webworker.importscripts.d.ts, --, --)) + diff --git a/tests/baselines/reference/noParameterReassignmentJSIIFE.types b/tests/baselines/reference/noParameterReassignmentJSIIFE.types new file mode 100644 index 00000000000..bb447e31f33 --- /dev/null +++ b/tests/baselines/reference/noParameterReassignmentJSIIFE.types @@ -0,0 +1,26 @@ +=== tests/cases/compiler/index.js === +self.importScripts = (function (importScripts) { +>self.importScripts = (function (importScripts) { return function () { return importScripts.apply(this, arguments); };})(importScripts) : (...args: string[]) => any +>self.importScripts : (...urls: string[]) => void +>self : Window & typeof globalThis +>importScripts : (...urls: string[]) => void +>(function (importScripts) { return function () { return importScripts.apply(this, arguments); };})(importScripts) : (...args: string[]) => any +>(function (importScripts) { return function () { return importScripts.apply(this, arguments); };}) : (importScripts: (...urls: string[]) => void) => (...args: string[]) => any +>function (importScripts) { return function () { return importScripts.apply(this, arguments); };} : (importScripts: (...urls: string[]) => void) => (...args: string[]) => any +>importScripts : (...urls: string[]) => void + + return function () { +>function () { return importScripts.apply(this, arguments); } : (...args: string[]) => any + + return importScripts.apply(this, arguments); +>importScripts.apply(this, arguments) : any +>importScripts.apply : (this: Function, thisArg: any, argArray?: any) => any +>importScripts : (...urls: string[]) => void +>apply : (this: Function, thisArg: any, argArray?: any) => any +>this : any +>arguments : IArguments + + }; +})(importScripts); +>importScripts : (...urls: string[]) => void + diff --git a/tests/baselines/reference/plainJSGrammarErrors2.js b/tests/baselines/reference/plainJSGrammarErrors2.js new file mode 100644 index 00000000000..501dd231c19 --- /dev/null +++ b/tests/baselines/reference/plainJSGrammarErrors2.js @@ -0,0 +1,22 @@ +//// [tests/cases/conformance/salsa/plainJSGrammarErrors2.ts] //// + +//// [plainJSGrammarErrors2.js] + +//// [a.js] +export default 1; + +//// [b.js] +/** + * @deprecated + */ +export { default as A } from "./a"; + + +//// [plainJSGrammarErrors2.js] +//// [a.js] +export default 1; +//// [b.js] +/** + * @deprecated + */ +export { default as A } from "./a"; diff --git a/tests/baselines/reference/plainJSGrammarErrors2.symbols b/tests/baselines/reference/plainJSGrammarErrors2.symbols new file mode 100644 index 00000000000..d4186554ad0 --- /dev/null +++ b/tests/baselines/reference/plainJSGrammarErrors2.symbols @@ -0,0 +1,13 @@ +=== tests/cases/conformance/salsa/plainJSGrammarErrors2.js === + +No type information for this code.=== /a.js === +export default 1; +No type information for this code. +No type information for this code.=== /b.js === +/** + * @deprecated + */ +export { default as A } from "./a"; +>default : Symbol(default, Decl(a.js, 0, 0)) +>A : Symbol(A, Decl(b.js, 3, 8)) + diff --git a/tests/baselines/reference/plainJSGrammarErrors2.types b/tests/baselines/reference/plainJSGrammarErrors2.types new file mode 100644 index 00000000000..d2c6ae93364 --- /dev/null +++ b/tests/baselines/reference/plainJSGrammarErrors2.types @@ -0,0 +1,13 @@ +=== tests/cases/conformance/salsa/plainJSGrammarErrors2.js === + +No type information for this code.=== /a.js === +export default 1; +No type information for this code. +No type information for this code.=== /b.js === +/** + * @deprecated + */ +export { default as A } from "./a"; +>default : 1 +>A : 1 + diff --git a/tests/baselines/reference/quickInfoJsDocTags3.baseline b/tests/baselines/reference/quickInfoJsDocTags3.baseline index 7d4ace62092..ab71bea1697 100644 --- a/tests/baselines/reference/quickInfoJsDocTags3.baseline +++ b/tests/baselines/reference/quickInfoJsDocTags3.baseline @@ -107,7 +107,7 @@ "kind": "space" }, { - "text": "x comment", + "text": "- x comment", "kind": "text" } ] @@ -124,7 +124,7 @@ "kind": "space" }, { - "text": "y comment", + "text": "- y comment", "kind": "text" } ] diff --git a/tests/baselines/reference/quickInfoJsDocTags4.baseline b/tests/baselines/reference/quickInfoJsDocTags4.baseline index 21d1f8417ef..097ac25f124 100644 --- a/tests/baselines/reference/quickInfoJsDocTags4.baseline +++ b/tests/baselines/reference/quickInfoJsDocTags4.baseline @@ -147,7 +147,7 @@ "kind": "space" }, { - "text": "x comment", + "text": "- x comment", "kind": "text" } ] @@ -164,7 +164,7 @@ "kind": "space" }, { - "text": "y comment", + "text": "- y comment", "kind": "text" } ] diff --git a/tests/baselines/reference/quickInfoJsDocTags5.baseline b/tests/baselines/reference/quickInfoJsDocTags5.baseline index ce728153bd0..167f3df4918 100644 --- a/tests/baselines/reference/quickInfoJsDocTags5.baseline +++ b/tests/baselines/reference/quickInfoJsDocTags5.baseline @@ -147,7 +147,7 @@ "kind": "space" }, { - "text": "x comment", + "text": "- x comment", "kind": "text" } ] @@ -164,7 +164,7 @@ "kind": "space" }, { - "text": "y comment", + "text": "- y comment", "kind": "text" } ] diff --git a/tests/baselines/reference/quickInfoJsDocTags6.baseline b/tests/baselines/reference/quickInfoJsDocTags6.baseline index 290ba10c04f..7ab1d074034 100644 --- a/tests/baselines/reference/quickInfoJsDocTags6.baseline +++ b/tests/baselines/reference/quickInfoJsDocTags6.baseline @@ -147,7 +147,7 @@ "kind": "space" }, { - "text": "x comment", + "text": "- x comment", "kind": "text" } ] @@ -164,7 +164,7 @@ "kind": "space" }, { - "text": "y comment", + "text": "- y comment", "kind": "text" } ] diff --git a/tests/baselines/reference/signatureHelpJSDocCallbackTag.baseline b/tests/baselines/reference/signatureHelpJSDocCallbackTag.baseline index 02c3b676798..640c0c7dc1e 100644 --- a/tests/baselines/reference/signatureHelpJSDocCallbackTag.baseline +++ b/tests/baselines/reference/signatureHelpJSDocCallbackTag.baseline @@ -52,7 +52,7 @@ "name": "eventName", "documentation": [ { - "text": "So many words", + "text": "- So many words", "kind": "text" } ], @@ -81,7 +81,7 @@ "name": "eventName2", "documentation": [ { - "text": "Silence is golden", + "text": "- Silence is golden", "kind": "text" } ], @@ -126,7 +126,7 @@ "name": "eventName3", "documentation": [ { - "text": "Osterreich mos def", + "text": "- Osterreich mos def", "kind": "text" } ], @@ -234,7 +234,7 @@ "name": "eventName", "documentation": [ { - "text": "So many words", + "text": "- So many words", "kind": "text" } ], @@ -263,7 +263,7 @@ "name": "eventName2", "documentation": [ { - "text": "Silence is golden", + "text": "- Silence is golden", "kind": "text" } ], @@ -308,7 +308,7 @@ "name": "eventName3", "documentation": [ { - "text": "Osterreich mos def", + "text": "- Osterreich mos def", "kind": "text" } ], @@ -416,7 +416,7 @@ "name": "eventName", "documentation": [ { - "text": "So many words", + "text": "- So many words", "kind": "text" } ], @@ -445,7 +445,7 @@ "name": "eventName2", "documentation": [ { - "text": "Silence is golden", + "text": "- Silence is golden", "kind": "text" } ], @@ -490,7 +490,7 @@ "name": "eventName3", "documentation": [ { - "text": "Osterreich mos def", + "text": "- Osterreich mos def", "kind": "text" } ], diff --git a/tests/baselines/reference/templateLiteralIntersection.js b/tests/baselines/reference/templateLiteralIntersection.js new file mode 100644 index 00000000000..24a5a684a2e --- /dev/null +++ b/tests/baselines/reference/templateLiteralIntersection.js @@ -0,0 +1,33 @@ +//// [templateLiteralIntersection.ts] +// https://github.com/microsoft/TypeScript/issues/48034 +const a = 'a' + +type A = typeof a +type MixA = A & {foo: string} + +type OriginA1 = `${A}` +type OriginA2 = `${MixA}` + +type B = `${typeof a}` +type MixB = B & { foo: string } + +type OriginB1 = `${B}` +type OriginB2 = `${MixB}` + +type MixC = { foo: string } & A + +type OriginC = `${MixC}` + +type MixD = + `${T & { foo: string }}` +type OriginD = `${MixD & { foo: string }}`; + +type E = `${A & {}}`; +type MixE = E & {} +type OriginE = `${MixE}` + +type OriginF = `${A}foo${A}`; + +//// [templateLiteralIntersection.js] +// https://github.com/microsoft/TypeScript/issues/48034 +var a = 'a'; diff --git a/tests/baselines/reference/templateLiteralIntersection.symbols b/tests/baselines/reference/templateLiteralIntersection.symbols new file mode 100644 index 00000000000..031b081d203 --- /dev/null +++ b/tests/baselines/reference/templateLiteralIntersection.symbols @@ -0,0 +1,80 @@ +=== tests/cases/compiler/templateLiteralIntersection.ts === +// https://github.com/microsoft/TypeScript/issues/48034 +const a = 'a' +>a : Symbol(a, Decl(templateLiteralIntersection.ts, 1, 5)) + +type A = typeof a +>A : Symbol(A, Decl(templateLiteralIntersection.ts, 1, 13)) +>a : Symbol(a, Decl(templateLiteralIntersection.ts, 1, 5)) + +type MixA = A & {foo: string} +>MixA : Symbol(MixA, Decl(templateLiteralIntersection.ts, 3, 17)) +>A : Symbol(A, Decl(templateLiteralIntersection.ts, 1, 13)) +>foo : Symbol(foo, Decl(templateLiteralIntersection.ts, 4, 17)) + +type OriginA1 = `${A}` +>OriginA1 : Symbol(OriginA1, Decl(templateLiteralIntersection.ts, 4, 29)) +>A : Symbol(A, Decl(templateLiteralIntersection.ts, 1, 13)) + +type OriginA2 = `${MixA}` +>OriginA2 : Symbol(OriginA2, Decl(templateLiteralIntersection.ts, 6, 22)) +>MixA : Symbol(MixA, Decl(templateLiteralIntersection.ts, 3, 17)) + +type B = `${typeof a}` +>B : Symbol(B, Decl(templateLiteralIntersection.ts, 7, 25)) +>a : Symbol(a, Decl(templateLiteralIntersection.ts, 1, 5)) + +type MixB = B & { foo: string } +>MixB : Symbol(MixB, Decl(templateLiteralIntersection.ts, 9, 22)) +>B : Symbol(B, Decl(templateLiteralIntersection.ts, 7, 25)) +>foo : Symbol(foo, Decl(templateLiteralIntersection.ts, 10, 17)) + +type OriginB1 = `${B}` +>OriginB1 : Symbol(OriginB1, Decl(templateLiteralIntersection.ts, 10, 31)) +>B : Symbol(B, Decl(templateLiteralIntersection.ts, 7, 25)) + +type OriginB2 = `${MixB}` +>OriginB2 : Symbol(OriginB2, Decl(templateLiteralIntersection.ts, 12, 22)) +>MixB : Symbol(MixB, Decl(templateLiteralIntersection.ts, 9, 22)) + +type MixC = { foo: string } & A +>MixC : Symbol(MixC, Decl(templateLiteralIntersection.ts, 13, 25)) +>foo : Symbol(foo, Decl(templateLiteralIntersection.ts, 15, 13)) +>A : Symbol(A, Decl(templateLiteralIntersection.ts, 1, 13)) + +type OriginC = `${MixC}` +>OriginC : Symbol(OriginC, Decl(templateLiteralIntersection.ts, 15, 31)) +>MixC : Symbol(MixC, Decl(templateLiteralIntersection.ts, 13, 25)) + +type MixD = +>MixD : Symbol(MixD, Decl(templateLiteralIntersection.ts, 17, 24)) +>T : Symbol(T, Decl(templateLiteralIntersection.ts, 19, 10)) + + `${T & { foo: string }}` +>T : Symbol(T, Decl(templateLiteralIntersection.ts, 19, 10)) +>foo : Symbol(foo, Decl(templateLiteralIntersection.ts, 20, 12)) + +type OriginD = `${MixD & { foo: string }}`; +>OriginD : Symbol(OriginD, Decl(templateLiteralIntersection.ts, 20, 28)) +>MixD : Symbol(MixD, Decl(templateLiteralIntersection.ts, 17, 24)) +>A : Symbol(A, Decl(templateLiteralIntersection.ts, 1, 13)) +>foo : Symbol(foo, Decl(templateLiteralIntersection.ts, 21, 28)) +>foo : Symbol(foo, Decl(templateLiteralIntersection.ts, 21, 47)) + +type E = `${A & {}}`; +>E : Symbol(E, Decl(templateLiteralIntersection.ts, 21, 64)) +>A : Symbol(A, Decl(templateLiteralIntersection.ts, 1, 13)) + +type MixE = E & {} +>MixE : Symbol(MixE, Decl(templateLiteralIntersection.ts, 23, 21)) +>E : Symbol(E, Decl(templateLiteralIntersection.ts, 21, 64)) + +type OriginE = `${MixE}` +>OriginE : Symbol(OriginE, Decl(templateLiteralIntersection.ts, 24, 18)) +>MixE : Symbol(MixE, Decl(templateLiteralIntersection.ts, 23, 21)) + +type OriginF = `${A}foo${A}`; +>OriginF : Symbol(OriginF, Decl(templateLiteralIntersection.ts, 25, 24)) +>A : Symbol(A, Decl(templateLiteralIntersection.ts, 1, 13)) +>A : Symbol(A, Decl(templateLiteralIntersection.ts, 1, 13)) + diff --git a/tests/baselines/reference/templateLiteralIntersection.types b/tests/baselines/reference/templateLiteralIntersection.types new file mode 100644 index 00000000000..d675ad0e0eb --- /dev/null +++ b/tests/baselines/reference/templateLiteralIntersection.types @@ -0,0 +1,64 @@ +=== tests/cases/compiler/templateLiteralIntersection.ts === +// https://github.com/microsoft/TypeScript/issues/48034 +const a = 'a' +>a : "a" +>'a' : "a" + +type A = typeof a +>A : "a" +>a : "a" + +type MixA = A & {foo: string} +>MixA : MixA +>foo : string + +type OriginA1 = `${A}` +>OriginA1 : "a" + +type OriginA2 = `${MixA}` +>OriginA2 : "a" + +type B = `${typeof a}` +>B : "a" +>a : "a" + +type MixB = B & { foo: string } +>MixB : MixB +>foo : string + +type OriginB1 = `${B}` +>OriginB1 : "a" + +type OriginB2 = `${MixB}` +>OriginB2 : "a" + +type MixC = { foo: string } & A +>MixC : MixC +>foo : string + +type OriginC = `${MixC}` +>OriginC : "a" + +type MixD = +>MixD : `${T & { foo: string; }}` + + `${T & { foo: string }}` +>foo : string + +type OriginD = `${MixD & { foo: string }}`; +>OriginD : "a" +>foo : string +>foo : string + +type E = `${A & {}}`; +>E : "a" + +type MixE = E & {} +>MixE : MixE + +type OriginE = `${MixE}` +>OriginE : "a" + +type OriginF = `${A}foo${A}`; +>OriginF : "afooa" + diff --git a/tests/baselines/reference/truthinessCallExpressionCoercion4.symbols b/tests/baselines/reference/truthinessCallExpressionCoercion4.symbols new file mode 100644 index 00000000000..da41aefd1a3 --- /dev/null +++ b/tests/baselines/reference/truthinessCallExpressionCoercion4.symbols @@ -0,0 +1,17 @@ +=== tests/cases/compiler/a.js === +function fn() {} +>fn : Symbol(fn, Decl(a.js, 0, 0)) + +if (typeof module === 'object' && module.exports) { +>module : Symbol(module, Decl(a.js, 2, 51)) +>module.exports : Symbol(module.exports, Decl(a.js, 0, 0)) +>module : Symbol(module, Decl(a.js, 2, 51)) +>exports : Symbol(module.exports, Decl(a.js, 0, 0)) + + module.exports = fn; +>module.exports : Symbol(module.exports, Decl(a.js, 0, 0)) +>module : Symbol(export=, Decl(a.js, 2, 51)) +>exports : Symbol(export=, Decl(a.js, 2, 51)) +>fn : Symbol(fn, Decl(a.js, 0, 0)) +} + diff --git a/tests/baselines/reference/truthinessCallExpressionCoercion4.types b/tests/baselines/reference/truthinessCallExpressionCoercion4.types new file mode 100644 index 00000000000..d9a0f16b912 --- /dev/null +++ b/tests/baselines/reference/truthinessCallExpressionCoercion4.types @@ -0,0 +1,22 @@ +=== tests/cases/compiler/a.js === +function fn() {} +>fn : () => void + +if (typeof module === 'object' && module.exports) { +>typeof module === 'object' && module.exports : false | (() => void) +>typeof module === 'object' : boolean +>typeof module : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>module : { exports: () => void; } +>'object' : "object" +>module.exports : () => void +>module : { exports: () => void; } +>exports : () => void + + module.exports = fn; +>module.exports = fn : () => void +>module.exports : () => void +>module : { exports: () => void; } +>exports : () => void +>fn : () => void +} + diff --git a/tests/baselines/reference/tsConfig/Default initialized TSConfig/tsconfig.json b/tests/baselines/reference/tsConfig/Default initialized TSConfig/tsconfig.json index e477a6d2d0f..cbb0ee6006b 100644 --- a/tests/baselines/reference/tsConfig/Default initialized TSConfig/tsconfig.json +++ b/tests/baselines/reference/tsConfig/Default initialized TSConfig/tsconfig.json @@ -5,7 +5,7 @@ /* Projects */ // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */ // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */ - // "tsBuildInfoFile": "./", /* Specify the folder for .tsbuildinfo incremental compilation files. */ + // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */ // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */ // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */ // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */ diff --git a/tests/baselines/reference/tsConfig/Initialized TSConfig with advanced options/tsconfig.json b/tests/baselines/reference/tsConfig/Initialized TSConfig with advanced options/tsconfig.json index 79809e53b7f..86ed001f09e 100644 --- a/tests/baselines/reference/tsConfig/Initialized TSConfig with advanced options/tsconfig.json +++ b/tests/baselines/reference/tsConfig/Initialized TSConfig with advanced options/tsconfig.json @@ -5,7 +5,7 @@ /* Projects */ // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */ // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */ - // "tsBuildInfoFile": "./", /* Specify the folder for .tsbuildinfo incremental compilation files. */ + // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */ // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */ // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */ // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */ diff --git a/tests/baselines/reference/tsConfig/Initialized TSConfig with boolean value compiler options/tsconfig.json b/tests/baselines/reference/tsConfig/Initialized TSConfig with boolean value compiler options/tsconfig.json index ec639ce04b5..389fcc9ae57 100644 --- a/tests/baselines/reference/tsConfig/Initialized TSConfig with boolean value compiler options/tsconfig.json +++ b/tests/baselines/reference/tsConfig/Initialized TSConfig with boolean value compiler options/tsconfig.json @@ -5,7 +5,7 @@ /* Projects */ // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */ // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */ - // "tsBuildInfoFile": "./", /* Specify the folder for .tsbuildinfo incremental compilation files. */ + // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */ // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */ // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */ // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */ diff --git a/tests/baselines/reference/tsConfig/Initialized TSConfig with enum value compiler options/tsconfig.json b/tests/baselines/reference/tsConfig/Initialized TSConfig with enum value compiler options/tsconfig.json index 0870344d037..e6093373399 100644 --- a/tests/baselines/reference/tsConfig/Initialized TSConfig with enum value compiler options/tsconfig.json +++ b/tests/baselines/reference/tsConfig/Initialized TSConfig with enum value compiler options/tsconfig.json @@ -5,7 +5,7 @@ /* Projects */ // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */ // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */ - // "tsBuildInfoFile": "./", /* Specify the folder for .tsbuildinfo incremental compilation files. */ + // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */ // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */ // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */ // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */ diff --git a/tests/baselines/reference/tsConfig/Initialized TSConfig with files options/tsconfig.json b/tests/baselines/reference/tsConfig/Initialized TSConfig with files options/tsconfig.json index eb7b0a8f38d..2e4c6821205 100644 --- a/tests/baselines/reference/tsConfig/Initialized TSConfig with files options/tsconfig.json +++ b/tests/baselines/reference/tsConfig/Initialized TSConfig with files options/tsconfig.json @@ -5,7 +5,7 @@ /* Projects */ // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */ // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */ - // "tsBuildInfoFile": "./", /* Specify the folder for .tsbuildinfo incremental compilation files. */ + // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */ // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */ // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */ // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */ diff --git a/tests/baselines/reference/tsConfig/Initialized TSConfig with incorrect compiler option value/tsconfig.json b/tests/baselines/reference/tsConfig/Initialized TSConfig with incorrect compiler option value/tsconfig.json index 8ebd3a89cb7..28793103db7 100644 --- a/tests/baselines/reference/tsConfig/Initialized TSConfig with incorrect compiler option value/tsconfig.json +++ b/tests/baselines/reference/tsConfig/Initialized TSConfig with incorrect compiler option value/tsconfig.json @@ -5,7 +5,7 @@ /* Projects */ // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */ // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */ - // "tsBuildInfoFile": "./", /* Specify the folder for .tsbuildinfo incremental compilation files. */ + // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */ // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */ // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */ // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */ diff --git a/tests/baselines/reference/tsConfig/Initialized TSConfig with incorrect compiler option/tsconfig.json b/tests/baselines/reference/tsConfig/Initialized TSConfig with incorrect compiler option/tsconfig.json index e477a6d2d0f..cbb0ee6006b 100644 --- a/tests/baselines/reference/tsConfig/Initialized TSConfig with incorrect compiler option/tsconfig.json +++ b/tests/baselines/reference/tsConfig/Initialized TSConfig with incorrect compiler option/tsconfig.json @@ -5,7 +5,7 @@ /* Projects */ // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */ // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */ - // "tsBuildInfoFile": "./", /* Specify the folder for .tsbuildinfo incremental compilation files. */ + // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */ // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */ // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */ // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */ diff --git a/tests/baselines/reference/tsConfig/Initialized TSConfig with list compiler options with enum value/tsconfig.json b/tests/baselines/reference/tsConfig/Initialized TSConfig with list compiler options with enum value/tsconfig.json index 89fa7a41f98..1be4be4310f 100644 --- a/tests/baselines/reference/tsConfig/Initialized TSConfig with list compiler options with enum value/tsconfig.json +++ b/tests/baselines/reference/tsConfig/Initialized TSConfig with list compiler options with enum value/tsconfig.json @@ -5,7 +5,7 @@ /* Projects */ // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */ // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */ - // "tsBuildInfoFile": "./", /* Specify the folder for .tsbuildinfo incremental compilation files. */ + // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */ // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */ // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */ // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */ diff --git a/tests/baselines/reference/tsConfig/Initialized TSConfig with list compiler options/tsconfig.json b/tests/baselines/reference/tsConfig/Initialized TSConfig with list compiler options/tsconfig.json index 0d26d725aab..cf719724a9b 100644 --- a/tests/baselines/reference/tsConfig/Initialized TSConfig with list compiler options/tsconfig.json +++ b/tests/baselines/reference/tsConfig/Initialized TSConfig with list compiler options/tsconfig.json @@ -5,7 +5,7 @@ /* Projects */ // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */ // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */ - // "tsBuildInfoFile": "./", /* Specify the folder for .tsbuildinfo incremental compilation files. */ + // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */ // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */ // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */ // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */ diff --git a/tests/baselines/reference/tscWatch/programUpdates/should-not-trigger-recompilation-because-of-program-emit/declarationDir-is-specified.js b/tests/baselines/reference/tscWatch/programUpdates/should-not-trigger-recompilation-because-of-program-emit/declarationDir-is-specified.js index 6726890d7f2..999ad0d42f9 100644 --- a/tests/baselines/reference/tscWatch/programUpdates/should-not-trigger-recompilation-because-of-program-emit/declarationDir-is-specified.js +++ b/tests/baselines/reference/tscWatch/programUpdates/should-not-trigger-recompilation-because-of-program-emit/declarationDir-is-specified.js @@ -26,7 +26,7 @@ interface Array { length: number; [n: number]: T; } /* Projects */ // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */ // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */ - // "tsBuildInfoFile": "./", /* Specify the folder for .tsbuildinfo incremental compilation files. */ + // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */ // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */ // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */ // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */ diff --git a/tests/baselines/reference/tscWatch/programUpdates/should-not-trigger-recompilation-because-of-program-emit/when-outDir-and-declarationDir-is-specified.js b/tests/baselines/reference/tscWatch/programUpdates/should-not-trigger-recompilation-because-of-program-emit/when-outDir-and-declarationDir-is-specified.js index 4eb22035026..1ded750e98a 100644 --- a/tests/baselines/reference/tscWatch/programUpdates/should-not-trigger-recompilation-because-of-program-emit/when-outDir-and-declarationDir-is-specified.js +++ b/tests/baselines/reference/tscWatch/programUpdates/should-not-trigger-recompilation-because-of-program-emit/when-outDir-and-declarationDir-is-specified.js @@ -26,7 +26,7 @@ interface Array { length: number; [n: number]: T; } /* Projects */ // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */ // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */ - // "tsBuildInfoFile": "./", /* Specify the folder for .tsbuildinfo incremental compilation files. */ + // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */ // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */ // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */ // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */ diff --git a/tests/baselines/reference/tscWatch/programUpdates/should-not-trigger-recompilation-because-of-program-emit/when-outDir-is-specified.js b/tests/baselines/reference/tscWatch/programUpdates/should-not-trigger-recompilation-because-of-program-emit/when-outDir-is-specified.js index bb93a691e97..4fc52ed5c18 100644 --- a/tests/baselines/reference/tscWatch/programUpdates/should-not-trigger-recompilation-because-of-program-emit/when-outDir-is-specified.js +++ b/tests/baselines/reference/tscWatch/programUpdates/should-not-trigger-recompilation-because-of-program-emit/when-outDir-is-specified.js @@ -26,7 +26,7 @@ interface Array { length: number; [n: number]: T; } /* Projects */ // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */ // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */ - // "tsBuildInfoFile": "./", /* Specify the folder for .tsbuildinfo incremental compilation files. */ + // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */ // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */ // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */ // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */ diff --git a/tests/baselines/reference/tscWatch/programUpdates/should-not-trigger-recompilation-because-of-program-emit/with-outFile.js b/tests/baselines/reference/tscWatch/programUpdates/should-not-trigger-recompilation-because-of-program-emit/with-outFile.js index bcfb9f12b5a..cf62b7b0e53 100644 --- a/tests/baselines/reference/tscWatch/programUpdates/should-not-trigger-recompilation-because-of-program-emit/with-outFile.js +++ b/tests/baselines/reference/tscWatch/programUpdates/should-not-trigger-recompilation-because-of-program-emit/with-outFile.js @@ -26,7 +26,7 @@ interface Array { length: number; [n: number]: T; } /* Projects */ // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */ // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */ - // "tsBuildInfoFile": "./", /* Specify the folder for .tsbuildinfo incremental compilation files. */ + // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */ // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */ // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */ // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */ diff --git a/tests/baselines/reference/tscWatch/programUpdates/should-not-trigger-recompilation-because-of-program-emit/without-outDir-or-outFile-is-specified-with-declaration-enabled.js b/tests/baselines/reference/tscWatch/programUpdates/should-not-trigger-recompilation-because-of-program-emit/without-outDir-or-outFile-is-specified-with-declaration-enabled.js index c123aec942b..0894634ccac 100644 --- a/tests/baselines/reference/tscWatch/programUpdates/should-not-trigger-recompilation-because-of-program-emit/without-outDir-or-outFile-is-specified-with-declaration-enabled.js +++ b/tests/baselines/reference/tscWatch/programUpdates/should-not-trigger-recompilation-because-of-program-emit/without-outDir-or-outFile-is-specified-with-declaration-enabled.js @@ -26,7 +26,7 @@ interface Array { length: number; [n: number]: T; } /* Projects */ // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */ // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */ - // "tsBuildInfoFile": "./", /* Specify the folder for .tsbuildinfo incremental compilation files. */ + // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */ // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */ // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */ // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */ diff --git a/tests/baselines/reference/tscWatch/programUpdates/should-not-trigger-recompilation-because-of-program-emit/without-outDir-or-outFile-is-specified.js b/tests/baselines/reference/tscWatch/programUpdates/should-not-trigger-recompilation-because-of-program-emit/without-outDir-or-outFile-is-specified.js index 346ddcce15a..e417e3ce35c 100644 --- a/tests/baselines/reference/tscWatch/programUpdates/should-not-trigger-recompilation-because-of-program-emit/without-outDir-or-outFile-is-specified.js +++ b/tests/baselines/reference/tscWatch/programUpdates/should-not-trigger-recompilation-because-of-program-emit/without-outDir-or-outFile-is-specified.js @@ -26,7 +26,7 @@ interface Array { length: number; [n: number]: T; } /* Projects */ // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */ // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */ - // "tsBuildInfoFile": "./", /* Specify the folder for .tsbuildinfo incremental compilation files. */ + // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */ // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */ // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */ // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */ diff --git a/tests/baselines/reference/tsxDiscriminantPropertyInference.js b/tests/baselines/reference/tsxDiscriminantPropertyInference.js index 39da73242f0..b374f4690b0 100644 --- a/tests/baselines/reference/tsxDiscriminantPropertyInference.js +++ b/tests/baselines/reference/tsxDiscriminantPropertyInference.js @@ -14,15 +14,9 @@ type DiscriminatorFalse = { cb: (x: number) => void; } -type Unrelated = { - val: number; -} - type Props = DiscriminatorTrue | DiscriminatorFalse; -type UnrelatedProps = Props | Unrelated; - -declare function Comp(props: Props): JSX.Element; +declare function Comp(props: DiscriminatorTrue | DiscriminatorFalse): JSX.Element; // simple inference void ( parseInt(s)} />); @@ -35,11 +29,6 @@ void ( n.toFixed()} />); // requires checking type information since discriminator is missing from object void ( n.toFixed()} />); - -declare function UnrelatedComp(props: UnrelatedProps): JSX.Element; - -// requires checking properties of all types, rather than properties of just the union type (e.g. only intersection) -void ( n.toFixed()} />); //// [tsxDiscriminantPropertyInference.jsx] @@ -51,5 +40,3 @@ void (); void (); // requires checking type information since discriminator is missing from object void (); -// requires checking properties of all types, rather than properties of just the union type (e.g. only intersection) -void (); diff --git a/tests/baselines/reference/tsxDiscriminantPropertyInference.symbols b/tests/baselines/reference/tsxDiscriminantPropertyInference.symbols index d7a1f94ae71..4b74166e91b 100644 --- a/tests/baselines/reference/tsxDiscriminantPropertyInference.symbols +++ b/tests/baselines/reference/tsxDiscriminantPropertyInference.symbols @@ -29,82 +29,55 @@ type DiscriminatorFalse = { >x : Symbol(x, Decl(tsxDiscriminantPropertyInference.tsx, 12, 9)) } -type Unrelated = { ->Unrelated : Symbol(Unrelated, Decl(tsxDiscriminantPropertyInference.tsx, 13, 1)) - - val: number; ->val : Symbol(val, Decl(tsxDiscriminantPropertyInference.tsx, 15, 18)) -} - type Props = DiscriminatorTrue | DiscriminatorFalse; ->Props : Symbol(Props, Decl(tsxDiscriminantPropertyInference.tsx, 17, 1)) +>Props : Symbol(Props, Decl(tsxDiscriminantPropertyInference.tsx, 13, 1)) >DiscriminatorTrue : Symbol(DiscriminatorTrue, Decl(tsxDiscriminantPropertyInference.tsx, 3, 1)) >DiscriminatorFalse : Symbol(DiscriminatorFalse, Decl(tsxDiscriminantPropertyInference.tsx, 8, 1)) -type UnrelatedProps = Props | Unrelated; ->UnrelatedProps : Symbol(UnrelatedProps, Decl(tsxDiscriminantPropertyInference.tsx, 19, 52)) ->Props : Symbol(Props, Decl(tsxDiscriminantPropertyInference.tsx, 17, 1)) ->Unrelated : Symbol(Unrelated, Decl(tsxDiscriminantPropertyInference.tsx, 13, 1)) - -declare function Comp(props: Props): JSX.Element; ->Comp : Symbol(Comp, Decl(tsxDiscriminantPropertyInference.tsx, 21, 40)) ->props : Symbol(props, Decl(tsxDiscriminantPropertyInference.tsx, 23, 22)) ->Props : Symbol(Props, Decl(tsxDiscriminantPropertyInference.tsx, 17, 1)) +declare function Comp(props: DiscriminatorTrue | DiscriminatorFalse): JSX.Element; +>Comp : Symbol(Comp, Decl(tsxDiscriminantPropertyInference.tsx, 15, 52)) +>props : Symbol(props, Decl(tsxDiscriminantPropertyInference.tsx, 17, 22)) +>DiscriminatorTrue : Symbol(DiscriminatorTrue, Decl(tsxDiscriminantPropertyInference.tsx, 3, 1)) +>DiscriminatorFalse : Symbol(DiscriminatorFalse, Decl(tsxDiscriminantPropertyInference.tsx, 8, 1)) >JSX : Symbol(JSX, Decl(tsxDiscriminantPropertyInference.tsx, 0, 0)) >Element : Symbol(JSX.Element, Decl(tsxDiscriminantPropertyInference.tsx, 1, 15)) // simple inference void ( parseInt(s)} />); ->Comp : Symbol(Comp, Decl(tsxDiscriminantPropertyInference.tsx, 21, 40)) ->disc : Symbol(disc, Decl(tsxDiscriminantPropertyInference.tsx, 26, 11)) ->cb : Symbol(cb, Decl(tsxDiscriminantPropertyInference.tsx, 26, 16)) ->s : Symbol(s, Decl(tsxDiscriminantPropertyInference.tsx, 26, 21)) +>Comp : Symbol(Comp, Decl(tsxDiscriminantPropertyInference.tsx, 15, 52)) +>disc : Symbol(disc, Decl(tsxDiscriminantPropertyInference.tsx, 20, 11)) +>cb : Symbol(cb, Decl(tsxDiscriminantPropertyInference.tsx, 20, 16)) +>s : Symbol(s, Decl(tsxDiscriminantPropertyInference.tsx, 20, 21)) >parseInt : Symbol(parseInt, Decl(lib.es5.d.ts, --, --)) ->s : Symbol(s, Decl(tsxDiscriminantPropertyInference.tsx, 26, 21)) +>s : Symbol(s, Decl(tsxDiscriminantPropertyInference.tsx, 20, 21)) // simple inference void ( n.toFixed()} />); ->Comp : Symbol(Comp, Decl(tsxDiscriminantPropertyInference.tsx, 21, 40)) ->disc : Symbol(disc, Decl(tsxDiscriminantPropertyInference.tsx, 29, 11)) ->cb : Symbol(cb, Decl(tsxDiscriminantPropertyInference.tsx, 29, 24)) ->n : Symbol(n, Decl(tsxDiscriminantPropertyInference.tsx, 29, 29)) +>Comp : Symbol(Comp, Decl(tsxDiscriminantPropertyInference.tsx, 15, 52)) +>disc : Symbol(disc, Decl(tsxDiscriminantPropertyInference.tsx, 23, 11)) +>cb : Symbol(cb, Decl(tsxDiscriminantPropertyInference.tsx, 23, 24)) +>n : Symbol(n, Decl(tsxDiscriminantPropertyInference.tsx, 23, 29)) >n.toFixed : Symbol(Number.toFixed, Decl(lib.es5.d.ts, --, --)) ->n : Symbol(n, Decl(tsxDiscriminantPropertyInference.tsx, 29, 29)) +>n : Symbol(n, Decl(tsxDiscriminantPropertyInference.tsx, 23, 29)) >toFixed : Symbol(Number.toFixed, Decl(lib.es5.d.ts, --, --)) // simple inference when strict-null-checks are enabled void ( n.toFixed()} />); ->Comp : Symbol(Comp, Decl(tsxDiscriminantPropertyInference.tsx, 21, 40)) ->disc : Symbol(disc, Decl(tsxDiscriminantPropertyInference.tsx, 32, 11)) +>Comp : Symbol(Comp, Decl(tsxDiscriminantPropertyInference.tsx, 15, 52)) +>disc : Symbol(disc, Decl(tsxDiscriminantPropertyInference.tsx, 26, 11)) >undefined : Symbol(undefined) ->cb : Symbol(cb, Decl(tsxDiscriminantPropertyInference.tsx, 32, 28)) ->n : Symbol(n, Decl(tsxDiscriminantPropertyInference.tsx, 32, 33)) +>cb : Symbol(cb, Decl(tsxDiscriminantPropertyInference.tsx, 26, 28)) +>n : Symbol(n, Decl(tsxDiscriminantPropertyInference.tsx, 26, 33)) >n.toFixed : Symbol(Number.toFixed, Decl(lib.es5.d.ts, --, --)) ->n : Symbol(n, Decl(tsxDiscriminantPropertyInference.tsx, 32, 33)) +>n : Symbol(n, Decl(tsxDiscriminantPropertyInference.tsx, 26, 33)) >toFixed : Symbol(Number.toFixed, Decl(lib.es5.d.ts, --, --)) // requires checking type information since discriminator is missing from object void ( n.toFixed()} />); ->Comp : Symbol(Comp, Decl(tsxDiscriminantPropertyInference.tsx, 21, 40)) ->cb : Symbol(cb, Decl(tsxDiscriminantPropertyInference.tsx, 35, 11)) ->n : Symbol(n, Decl(tsxDiscriminantPropertyInference.tsx, 35, 16)) +>Comp : Symbol(Comp, Decl(tsxDiscriminantPropertyInference.tsx, 15, 52)) +>cb : Symbol(cb, Decl(tsxDiscriminantPropertyInference.tsx, 29, 11)) +>n : Symbol(n, Decl(tsxDiscriminantPropertyInference.tsx, 29, 16)) >n.toFixed : Symbol(Number.toFixed, Decl(lib.es5.d.ts, --, --)) ->n : Symbol(n, Decl(tsxDiscriminantPropertyInference.tsx, 35, 16)) ->toFixed : Symbol(Number.toFixed, Decl(lib.es5.d.ts, --, --)) - -declare function UnrelatedComp(props: UnrelatedProps): JSX.Element; ->UnrelatedComp : Symbol(UnrelatedComp, Decl(tsxDiscriminantPropertyInference.tsx, 35, 38)) ->props : Symbol(props, Decl(tsxDiscriminantPropertyInference.tsx, 37, 31)) ->UnrelatedProps : Symbol(UnrelatedProps, Decl(tsxDiscriminantPropertyInference.tsx, 19, 52)) ->JSX : Symbol(JSX, Decl(tsxDiscriminantPropertyInference.tsx, 0, 0)) ->Element : Symbol(JSX.Element, Decl(tsxDiscriminantPropertyInference.tsx, 1, 15)) - -// requires checking properties of all types, rather than properties of just the union type (e.g. only intersection) -void ( n.toFixed()} />); ->Comp : Symbol(Comp, Decl(tsxDiscriminantPropertyInference.tsx, 21, 40)) ->cb : Symbol(cb, Decl(tsxDiscriminantPropertyInference.tsx, 40, 11)) ->n : Symbol(n, Decl(tsxDiscriminantPropertyInference.tsx, 40, 16)) ->n.toFixed : Symbol(Number.toFixed, Decl(lib.es5.d.ts, --, --)) ->n : Symbol(n, Decl(tsxDiscriminantPropertyInference.tsx, 40, 16)) +>n : Symbol(n, Decl(tsxDiscriminantPropertyInference.tsx, 29, 16)) >toFixed : Symbol(Number.toFixed, Decl(lib.es5.d.ts, --, --)) diff --git a/tests/baselines/reference/tsxDiscriminantPropertyInference.types b/tests/baselines/reference/tsxDiscriminantPropertyInference.types index 49a89d29ef7..63932bd18d9 100644 --- a/tests/baselines/reference/tsxDiscriminantPropertyInference.types +++ b/tests/baselines/reference/tsxDiscriminantPropertyInference.types @@ -28,22 +28,12 @@ type DiscriminatorFalse = { >x : number } -type Unrelated = { ->Unrelated : Unrelated - - val: number; ->val : number -} - type Props = DiscriminatorTrue | DiscriminatorFalse; >Props : Props -type UnrelatedProps = Props | Unrelated; ->UnrelatedProps : UnrelatedProps - -declare function Comp(props: Props): JSX.Element; ->Comp : (props: Props) => JSX.Element ->props : Props +declare function Comp(props: DiscriminatorTrue | DiscriminatorFalse): JSX.Element; +>Comp : (props: DiscriminatorTrue | DiscriminatorFalse) => JSX.Element +>props : DiscriminatorTrue | DiscriminatorFalse >JSX : any // simple inference @@ -51,7 +41,7 @@ void ( parseInt(s)} />); >void ( parseInt(s)} />) : undefined >( parseInt(s)} />) : JSX.Element > parseInt(s)} /> : JSX.Element ->Comp : (props: Props) => JSX.Element +>Comp : (props: DiscriminatorTrue | DiscriminatorFalse) => JSX.Element >disc : true >cb : (s: string) => number >s => parseInt(s) : (s: string) => number @@ -65,7 +55,7 @@ void ( n.toFixed()} />); >void ( n.toFixed()} />) : undefined >( n.toFixed()} />) : JSX.Element > n.toFixed()} /> : JSX.Element ->Comp : (props: Props) => JSX.Element +>Comp : (props: DiscriminatorTrue | DiscriminatorFalse) => JSX.Element >disc : false >false : false >cb : (n: number) => string @@ -81,7 +71,7 @@ void ( n.toFixed()} />); >void ( n.toFixed()} />) : undefined >( n.toFixed()} />) : JSX.Element > n.toFixed()} /> : JSX.Element ->Comp : (props: Props) => JSX.Element +>Comp : (props: DiscriminatorTrue | DiscriminatorFalse) => JSX.Element >disc : undefined >undefined : undefined >cb : (n: number) => string @@ -97,26 +87,7 @@ void ( n.toFixed()} />); >void ( n.toFixed()} />) : undefined >( n.toFixed()} />) : JSX.Element > n.toFixed()} /> : JSX.Element ->Comp : (props: Props) => JSX.Element ->cb : (n: number) => string ->n => n.toFixed() : (n: number) => string ->n : number ->n.toFixed() : string ->n.toFixed : (fractionDigits?: number | undefined) => string ->n : number ->toFixed : (fractionDigits?: number | undefined) => string - -declare function UnrelatedComp(props: UnrelatedProps): JSX.Element; ->UnrelatedComp : (props: UnrelatedProps) => JSX.Element ->props : UnrelatedProps ->JSX : any - -// requires checking properties of all types, rather than properties of just the union type (e.g. only intersection) -void ( n.toFixed()} />); ->void ( n.toFixed()} />) : undefined ->( n.toFixed()} />) : JSX.Element -> n.toFixed()} /> : JSX.Element ->Comp : (props: Props) => JSX.Element +>Comp : (props: DiscriminatorTrue | DiscriminatorFalse) => JSX.Element >cb : (n: number) => string >n => n.toFixed() : (n: number) => string >n : number diff --git a/tests/baselines/reference/tsxNotUsingApparentTypeOfSFC.errors.txt b/tests/baselines/reference/tsxNotUsingApparentTypeOfSFC.errors.txt index 81231a34562..a967c92e555 100644 --- a/tests/baselines/reference/tsxNotUsingApparentTypeOfSFC.errors.txt +++ b/tests/baselines/reference/tsxNotUsingApparentTypeOfSFC.errors.txt @@ -5,9 +5,17 @@ tests/cases/compiler/tsxNotUsingApparentTypeOfSFC.tsx(15,14): error TS2769: No o Type '{}' is not assignable to type 'Readonly

'. Overload 2 of 2, '(props: P, context?: any): MyComponent', gave the following error. Type '{}' is not assignable to type 'Readonly

'. +tests/cases/compiler/tsxNotUsingApparentTypeOfSFC.tsx(17,14): error TS2322: Type 'P' is not assignable to type 'IntrinsicAttributes & P'. + Type 'P' is not assignable to type 'IntrinsicAttributes'. +tests/cases/compiler/tsxNotUsingApparentTypeOfSFC.tsx(18,14): error TS2769: No overload matches this call. + Overload 1 of 2, '(props: Readonly

): MyComponent', gave the following error. + Type 'P' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes & Readonly<{ children?: ReactNode; }> & Readonly

'. + Type 'P' is not assignable to type 'IntrinsicAttributes'. + Overload 2 of 2, '(props: P, context?: any): MyComponent', gave the following error. + Type 'P' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes & Readonly<{ children?: ReactNode; }> & Readonly

'. -==== tests/cases/compiler/tsxNotUsingApparentTypeOfSFC.tsx (2 errors) ==== +==== tests/cases/compiler/tsxNotUsingApparentTypeOfSFC.tsx (4 errors) ==== /// import React from 'react'; @@ -34,5 +42,17 @@ tests/cases/compiler/tsxNotUsingApparentTypeOfSFC.tsx(15,14): error TS2769: No o !!! error TS2769: Type '{}' is not assignable to type 'Readonly

'. let z = // should work + ~~~~~ +!!! error TS2322: Type 'P' is not assignable to type 'IntrinsicAttributes & P'. +!!! error TS2322: Type 'P' is not assignable to type 'IntrinsicAttributes'. +!!! related TS2208 tests/cases/compiler/tsxNotUsingApparentTypeOfSFC.tsx:5:15: This type parameter probably needs an `extends object` constraint. let q = // should work + ~~~~~~~~~~~ +!!! error TS2769: No overload matches this call. +!!! error TS2769: Overload 1 of 2, '(props: Readonly

): MyComponent', gave the following error. +!!! error TS2769: Type 'P' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes & Readonly<{ children?: ReactNode; }> & Readonly

'. +!!! error TS2769: Type 'P' is not assignable to type 'IntrinsicAttributes'. +!!! error TS2769: Overload 2 of 2, '(props: P, context?: any): MyComponent', gave the following error. +!!! error TS2769: Type 'P' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes & Readonly<{ children?: ReactNode; }> & Readonly

'. +!!! related TS2208 tests/cases/compiler/tsxNotUsingApparentTypeOfSFC.tsx:5:15: This type parameter probably needs an `extends object` constraint. } \ No newline at end of file diff --git a/tests/baselines/reference/uniqueSymbolsDeclarationsInJs.js b/tests/baselines/reference/uniqueSymbolsDeclarationsInJs.js index 3d0a68bbd3a..8d7f2afd6d5 100644 --- a/tests/baselines/reference/uniqueSymbolsDeclarationsInJs.js +++ b/tests/baselines/reference/uniqueSymbolsDeclarationsInJs.js @@ -23,6 +23,9 @@ class C { readonlyCall = Symbol(); readwriteCall = Symbol(); } + +/** @type {unique symbol} */ +const a = Symbol(); //// [uniqueSymbolsDeclarationsInJs-out.js] @@ -46,6 +49,8 @@ class C { static { this.readonlyStaticTypeAndCall = Symbol(); } static { this.readwriteStaticCall = Symbol(); } } +/** @type {unique symbol} */ +const a = Symbol(); //// [uniqueSymbolsDeclarationsInJs-out.d.ts] @@ -71,3 +76,5 @@ declare class C { readonly readonlyCall: symbol; readwriteCall: symbol; } +/** @type {unique symbol} */ +declare const a: unique symbol; diff --git a/tests/baselines/reference/uniqueSymbolsDeclarationsInJs.symbols b/tests/baselines/reference/uniqueSymbolsDeclarationsInJs.symbols index b48c5cc6c58..347389f2c81 100644 --- a/tests/baselines/reference/uniqueSymbolsDeclarationsInJs.symbols +++ b/tests/baselines/reference/uniqueSymbolsDeclarationsInJs.symbols @@ -41,3 +41,8 @@ class C { >Symbol : Symbol(Symbol, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2019.symbol.d.ts, --, --)) } +/** @type {unique symbol} */ +const a = Symbol(); +>a : Symbol(a, Decl(uniqueSymbolsDeclarationsInJs.js, 26, 5)) +>Symbol : Symbol(Symbol, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2019.symbol.d.ts, --, --)) + diff --git a/tests/baselines/reference/uniqueSymbolsDeclarationsInJs.types b/tests/baselines/reference/uniqueSymbolsDeclarationsInJs.types index a51ba3c324d..e4fa564ee8a 100644 --- a/tests/baselines/reference/uniqueSymbolsDeclarationsInJs.types +++ b/tests/baselines/reference/uniqueSymbolsDeclarationsInJs.types @@ -46,3 +46,9 @@ class C { >Symbol : SymbolConstructor } +/** @type {unique symbol} */ +const a = Symbol(); +>a : symbol +>Symbol() : unique symbol +>Symbol : SymbolConstructor + diff --git a/tests/baselines/reference/unknownType1.errors.txt b/tests/baselines/reference/unknownType1.errors.txt index 138fff847cc..39d7a1feb52 100644 --- a/tests/baselines/reference/unknownType1.errors.txt +++ b/tests/baselines/reference/unknownType1.errors.txt @@ -25,13 +25,14 @@ tests/cases/conformance/types/unknown/unknownType1.ts(144,29): error TS2698: Spr tests/cases/conformance/types/unknown/unknownType1.ts(150,17): error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value. tests/cases/conformance/types/unknown/unknownType1.ts(156,14): error TS2700: Rest types may only be created from object types. tests/cases/conformance/types/unknown/unknownType1.ts(162,5): error TS2564: Property 'a' has no initializer and is not definitely assigned in the constructor. +tests/cases/conformance/types/unknown/unknownType1.ts(170,9): error TS2322: Type 'T' is not assignable to type '{}'. tests/cases/conformance/types/unknown/unknownType1.ts(171,9): error TS2322: Type 'U' is not assignable to type '{}'. Type 'unknown' is not assignable to type '{}'. tests/cases/conformance/types/unknown/unknownType1.ts(181,5): error TS2322: Type 'T' is not assignable to type '{}'. Type 'unknown' is not assignable to type '{}'. -==== tests/cases/conformance/types/unknown/unknownType1.ts (27 errors) ==== +==== tests/cases/conformance/types/unknown/unknownType1.ts (28 errors) ==== // In an intersection everything absorbs unknown type T00 = unknown & null; // null @@ -254,6 +255,9 @@ tests/cases/conformance/types/unknown/unknownType1.ts(181,5): error TS2322: Type function f30(t: T, u: U) { let x: {} = t; + ~ +!!! error TS2322: Type 'T' is not assignable to type '{}'. +!!! related TS2208 tests/cases/conformance/types/unknown/unknownType1.ts:169:14: This type parameter probably needs an `extends object` constraint. let y: {} = u; ~ !!! error TS2322: Type 'U' is not assignable to type '{}'. diff --git a/tests/baselines/reference/varianceAnnotations.errors.txt b/tests/baselines/reference/varianceAnnotations.errors.txt new file mode 100644 index 00000000000..f1be2f615bb --- /dev/null +++ b/tests/baselines/reference/varianceAnnotations.errors.txt @@ -0,0 +1,307 @@ +tests/cases/conformance/types/typeParameters/typeParameterLists/varianceAnnotations.ts(9,1): error TS2322: Type 'Covariant' is not assignable to type 'Covariant'. + Type 'unknown' is not assignable to type 'string'. +tests/cases/conformance/types/typeParameters/typeParameterLists/varianceAnnotations.ts(18,1): error TS2322: Type 'Contravariant' is not assignable to type 'Contravariant'. + Type 'unknown' is not assignable to type 'string'. +tests/cases/conformance/types/typeParameters/typeParameterLists/varianceAnnotations.ts(28,1): error TS2322: Type 'Invariant' is not assignable to type 'Invariant'. + Types of property 'f' are incompatible. + Type '(x: string) => string' is not assignable to type '(x: unknown) => unknown'. + Types of parameters 'x' and 'x' are incompatible. + Type 'unknown' is not assignable to type 'string'. +tests/cases/conformance/types/typeParameters/typeParameterLists/varianceAnnotations.ts(29,1): error TS2322: Type 'Invariant' is not assignable to type 'Invariant'. + The types returned by 'f(...)' are incompatible between these types. + Type 'unknown' is not assignable to type 'string'. +tests/cases/conformance/types/typeParameters/typeParameterLists/varianceAnnotations.ts(40,17): error TS2636: Type 'Covariant1' is not assignable to type 'Covariant1' as implied by variance annotation. + Types of property 'x' are incompatible. + Type 'super-T' is not assignable to type 'sub-T'. +tests/cases/conformance/types/typeParameters/typeParameterLists/varianceAnnotations.ts(44,21): error TS2636: Type 'keyof sub-T' is not assignable to type 'keyof super-T' as implied by variance annotation. + Type 'string | number | symbol' is not assignable to type 'keyof super-T'. + Type 'string' is not assignable to type 'keyof super-T'. +tests/cases/conformance/types/typeParameters/typeParameterLists/varianceAnnotations.ts(46,21): error TS2636: Type 'Contravariant2' is not assignable to type 'Contravariant2' as implied by variance annotation. + Types of property 'f' are incompatible. + Type '(x: sub-T) => void' is not assignable to type '(x: super-T) => void'. + Types of parameters 'x' and 'x' are incompatible. + Type 'super-T' is not assignable to type 'sub-T'. +tests/cases/conformance/types/typeParameters/typeParameterLists/varianceAnnotations.ts(50,17): error TS2636: Type 'Invariant1' is not assignable to type 'Invariant1' as implied by variance annotation. + The types returned by 'f(...)' are incompatible between these types. + Type 'super-T' is not assignable to type 'sub-T'. +tests/cases/conformance/types/typeParameters/typeParameterLists/varianceAnnotations.ts(54,17): error TS2636: Type 'Invariant2' is not assignable to type 'Invariant2' as implied by variance annotation. + Types of property 'f' are incompatible. + Type '(x: sub-T) => sub-T' is not assignable to type '(x: super-T) => super-T'. + Types of parameters 'x' and 'x' are incompatible. + Type 'super-T' is not assignable to type 'sub-T'. +tests/cases/conformance/types/typeParameters/typeParameterLists/varianceAnnotations.ts(60,11): error TS2636: Type 'Foo1' is not assignable to type 'Foo1' as implied by variance annotation. + Types of property 'x' are incompatible. + Type 'super-T' is not assignable to type 'sub-T'. +tests/cases/conformance/types/typeParameters/typeParameterLists/varianceAnnotations.ts(71,11): error TS2636: Type 'Foo2' is not assignable to type 'Foo2' as implied by variance annotation. + Types of property 'f' are incompatible. + Type 'FooFn2' is not assignable to type 'FooFn2'. + Type 'super-T' is not assignable to type 'sub-T'. +tests/cases/conformance/types/typeParameters/typeParameterLists/varianceAnnotations.ts(95,10): error TS1273: 'public' modifier cannot appear on a type parameter +tests/cases/conformance/types/typeParameters/typeParameterLists/varianceAnnotations.ts(96,17): error TS1030: 'in' modifier already seen. +tests/cases/conformance/types/typeParameters/typeParameterLists/varianceAnnotations.ts(97,17): error TS1030: 'out' modifier already seen. +tests/cases/conformance/types/typeParameters/typeParameterLists/varianceAnnotations.ts(98,14): error TS1029: 'in' modifier must precede 'out' modifier. +tests/cases/conformance/types/typeParameters/typeParameterLists/varianceAnnotations.ts(100,21): error TS1274: 'in' modifier can only appear on a type parameter of a class, interface or type alias +tests/cases/conformance/types/typeParameters/typeParameterLists/varianceAnnotations.ts(101,21): error TS1274: 'out' modifier can only appear on a type parameter of a class, interface or type alias +tests/cases/conformance/types/typeParameters/typeParameterLists/varianceAnnotations.ts(104,5): error TS1274: 'in' modifier can only appear on a type parameter of a class, interface or type alias +tests/cases/conformance/types/typeParameters/typeParameterLists/varianceAnnotations.ts(105,5): error TS1274: 'out' modifier can only appear on a type parameter of a class, interface or type alias +tests/cases/conformance/types/typeParameters/typeParameterLists/varianceAnnotations.ts(116,1): error TS2322: Type 'Baz' is not assignable to type 'Baz'. + Type 'unknown' is not assignable to type 'string'. +tests/cases/conformance/types/typeParameters/typeParameterLists/varianceAnnotations.ts(117,1): error TS2322: Type 'Baz' is not assignable to type 'Baz'. + Type 'unknown' is not assignable to type 'string'. +tests/cases/conformance/types/typeParameters/typeParameterLists/varianceAnnotations.ts(136,7): error TS2322: Type 'Parent' is not assignable to type 'Parent'. + Type 'unknown' is not assignable to type 'string'. +tests/cases/conformance/types/typeParameters/typeParameterLists/varianceAnnotations.ts(160,68): error TS2345: Argument of type 'ActionObject<{ type: "PLAY"; value: number; }>' is not assignable to parameter of type 'ActionObject<{ type: "PLAY"; value: number; } | { type: "RESET"; }>'. + Types of property 'exec' are incompatible. + Type '(meta: StateNode) => void' is not assignable to type '(meta: StateNode) => void'. + Types of parameters 'meta' and 'meta' are incompatible. + Type 'StateNode' is not assignable to type 'StateNode'. + Types of property '_storedEvent' are incompatible. + Type '{ type: "PLAY"; value: number; } | { type: "RESET"; }' is not assignable to type '{ type: "PLAY"; value: number; }'. + Type '{ type: "RESET"; }' is not assignable to type '{ type: "PLAY"; value: number; }'. + + +==== tests/cases/conformance/types/typeParameters/typeParameterLists/varianceAnnotations.ts (23 errors) ==== + type Covariant = { + x: T; + } + + declare let super_covariant: Covariant; + declare let sub_covariant: Covariant; + + super_covariant = sub_covariant; + sub_covariant = super_covariant; // Error + ~~~~~~~~~~~~~ +!!! error TS2322: Type 'Covariant' is not assignable to type 'Covariant'. +!!! error TS2322: Type 'unknown' is not assignable to type 'string'. + + type Contravariant = { + f: (x: T) => void; + } + + declare let super_contravariant: Contravariant; + declare let sub_contravariant: Contravariant; + + super_contravariant = sub_contravariant; // Error + ~~~~~~~~~~~~~~~~~~~ +!!! error TS2322: Type 'Contravariant' is not assignable to type 'Contravariant'. +!!! error TS2322: Type 'unknown' is not assignable to type 'string'. + sub_contravariant = super_contravariant; + + type Invariant = { + f: (x: T) => T; + } + + declare let super_invariant: Invariant; + declare let sub_invariant: Invariant; + + super_invariant = sub_invariant; // Error + ~~~~~~~~~~~~~~~ +!!! error TS2322: Type 'Invariant' is not assignable to type 'Invariant'. +!!! error TS2322: Types of property 'f' are incompatible. +!!! error TS2322: Type '(x: string) => string' is not assignable to type '(x: unknown) => unknown'. +!!! error TS2322: Types of parameters 'x' and 'x' are incompatible. +!!! error TS2322: Type 'unknown' is not assignable to type 'string'. + sub_invariant = super_invariant; // Error + ~~~~~~~~~~~~~ +!!! error TS2322: Type 'Invariant' is not assignable to type 'Invariant'. +!!! error TS2322: The types returned by 'f(...)' are incompatible between these types. +!!! error TS2322: Type 'unknown' is not assignable to type 'string'. + + // Variance of various type constructors + + type T10 = T; + type T11 = keyof T; + type T12 = T[K]; + type T13 = T[keyof T]; + + // Variance annotation errors + + type Covariant1 = { // Error + ~~~~ +!!! error TS2636: Type 'Covariant1' is not assignable to type 'Covariant1' as implied by variance annotation. +!!! error TS2636: Types of property 'x' are incompatible. +!!! error TS2636: Type 'super-T' is not assignable to type 'sub-T'. + x: T; + } + + type Contravariant1 = keyof T; // Error + ~~~~~ +!!! error TS2636: Type 'keyof sub-T' is not assignable to type 'keyof super-T' as implied by variance annotation. +!!! error TS2636: Type 'string | number | symbol' is not assignable to type 'keyof super-T'. +!!! error TS2636: Type 'string' is not assignable to type 'keyof super-T'. + + type Contravariant2 = { // Error + ~~~~~ +!!! error TS2636: Type 'Contravariant2' is not assignable to type 'Contravariant2' as implied by variance annotation. +!!! error TS2636: Types of property 'f' are incompatible. +!!! error TS2636: Type '(x: sub-T) => void' is not assignable to type '(x: super-T) => void'. +!!! error TS2636: Types of parameters 'x' and 'x' are incompatible. +!!! error TS2636: Type 'super-T' is not assignable to type 'sub-T'. + f: (x: T) => void; + } + + type Invariant1 = { // Error + ~~~~ +!!! error TS2636: Type 'Invariant1' is not assignable to type 'Invariant1' as implied by variance annotation. +!!! error TS2636: The types returned by 'f(...)' are incompatible between these types. +!!! error TS2636: Type 'super-T' is not assignable to type 'sub-T'. + f: (x: T) => T; + } + + type Invariant2 = { // Error + ~~~~~ +!!! error TS2636: Type 'Invariant2' is not assignable to type 'Invariant2' as implied by variance annotation. +!!! error TS2636: Types of property 'f' are incompatible. +!!! error TS2636: Type '(x: sub-T) => sub-T' is not assignable to type '(x: super-T) => super-T'. +!!! error TS2636: Types of parameters 'x' and 'x' are incompatible. +!!! error TS2636: Type 'super-T' is not assignable to type 'sub-T'. + f: (x: T) => T; + } + + // Variance in circular types + + type Foo1 = { // Error + ~~~~ +!!! error TS2636: Type 'Foo1' is not assignable to type 'Foo1' as implied by variance annotation. +!!! error TS2636: Types of property 'x' are incompatible. +!!! error TS2636: Type 'super-T' is not assignable to type 'sub-T'. + x: T; + f: FooFn1; + } + + type FooFn1 = (foo: Bar1) => void; + + type Bar1 = { + value: Foo1; + } + + type Foo2 = { // Error + ~~~~~ +!!! error TS2636: Type 'Foo2' is not assignable to type 'Foo2' as implied by variance annotation. +!!! error TS2636: Types of property 'f' are incompatible. +!!! error TS2636: Type 'FooFn2' is not assignable to type 'FooFn2'. +!!! error TS2636: Type 'super-T' is not assignable to type 'sub-T'. + x: T; + f: FooFn2; + } + + type FooFn2 = (foo: Bar2) => void; + + type Bar2 = { + value: Foo2; + } + + type Foo3 = { + x: T; + f: FooFn3; + } + + type FooFn3 = (foo: Bar3) => void; + + type Bar3 = { + value: Foo3; + } + + // Wrong modifier usage + + type T20 = T; // Error + ~~~~~~ +!!! error TS1273: 'public' modifier cannot appear on a type parameter + type T21 = T; // Error + ~~ +!!! error TS1030: 'in' modifier already seen. + type T22 = T; // Error + ~~~ +!!! error TS1030: 'out' modifier already seen. + type T23 = T; // Error + ~~ +!!! error TS1029: 'in' modifier must precede 'out' modifier. + + declare function f1(x: T): void; // Error + ~~ +!!! error TS1274: 'in' modifier can only appear on a type parameter of a class, interface or type alias + declare function f2(): T; // Error + ~~~ +!!! error TS1274: 'out' modifier can only appear on a type parameter of a class, interface or type alias + + class C { + in a = 0; // Error + ~~ +!!! error TS1274: 'in' modifier can only appear on a type parameter of a class, interface or type alias + out b = 0; // Error + ~~~ +!!! error TS1274: 'out' modifier can only appear on a type parameter of a class, interface or type alias + } + + // Interface merging + + interface Baz {} + interface Baz {} + + declare let baz1: Baz; + declare let baz2: Baz; + + baz1 = baz2; // Error + ~~~~ +!!! error TS2322: Type 'Baz' is not assignable to type 'Baz'. +!!! error TS2322: Type 'unknown' is not assignable to type 'string'. + baz2 = baz1; // Error + ~~~~ +!!! error TS2322: Type 'Baz' is not assignable to type 'Baz'. +!!! error TS2322: Type 'unknown' is not assignable to type 'string'. + + // Repro from #44572 + + interface Parent { + child: Child | null; + parent: Parent | null; + } + + interface Child extends Parent { + readonly a: A; + readonly b: B; + } + + function fn(inp: Child) { + const a: Child = inp; + } + + const pu: Parent = { child: { a: 0, b: 0, child: null, parent: null }, parent: null }; + const notString: Parent = pu; // Error + ~~~~~~~~~ +!!! error TS2322: Type 'Parent' is not assignable to type 'Parent'. +!!! error TS2322: Type 'unknown' is not assignable to type 'string'. + + // Repro from comment in #44572 + + declare class StateNode { + _storedEvent: TEvent; + _action: ActionObject; + _state: StateNode; + } + + interface ActionObject { + exec: (meta: StateNode) => void; + } + + declare function createMachine(action: ActionObject): StateNode; + + declare function interpret(machine: StateNode): void; + + const machine = createMachine({} as any); + + interpret(machine); + + declare const qq: ActionObject<{ type: "PLAY"; value: number }>; + + createMachine<{ type: "PLAY"; value: number } | { type: "RESET" }>(qq); // Error + ~~ +!!! error TS2345: Argument of type 'ActionObject<{ type: "PLAY"; value: number; }>' is not assignable to parameter of type 'ActionObject<{ type: "PLAY"; value: number; } | { type: "RESET"; }>'. +!!! error TS2345: Types of property 'exec' are incompatible. +!!! error TS2345: Type '(meta: StateNode) => void' is not assignable to type '(meta: StateNode) => void'. +!!! error TS2345: Types of parameters 'meta' and 'meta' are incompatible. +!!! error TS2345: Type 'StateNode' is not assignable to type 'StateNode'. +!!! error TS2345: Types of property '_storedEvent' are incompatible. +!!! error TS2345: Type '{ type: "PLAY"; value: number; } | { type: "RESET"; }' is not assignable to type '{ type: "PLAY"; value: number; }'. +!!! error TS2345: Type '{ type: "RESET"; }' is not assignable to type '{ type: "PLAY"; value: number; }'. + \ No newline at end of file diff --git a/tests/baselines/reference/varianceAnnotations.js b/tests/baselines/reference/varianceAnnotations.js new file mode 100644 index 00000000000..7e3fac5285e --- /dev/null +++ b/tests/baselines/reference/varianceAnnotations.js @@ -0,0 +1,295 @@ +//// [varianceAnnotations.ts] +type Covariant = { + x: T; +} + +declare let super_covariant: Covariant; +declare let sub_covariant: Covariant; + +super_covariant = sub_covariant; +sub_covariant = super_covariant; // Error + +type Contravariant = { + f: (x: T) => void; +} + +declare let super_contravariant: Contravariant; +declare let sub_contravariant: Contravariant; + +super_contravariant = sub_contravariant; // Error +sub_contravariant = super_contravariant; + +type Invariant = { + f: (x: T) => T; +} + +declare let super_invariant: Invariant; +declare let sub_invariant: Invariant; + +super_invariant = sub_invariant; // Error +sub_invariant = super_invariant; // Error + +// Variance of various type constructors + +type T10 = T; +type T11 = keyof T; +type T12 = T[K]; +type T13 = T[keyof T]; + +// Variance annotation errors + +type Covariant1 = { // Error + x: T; +} + +type Contravariant1 = keyof T; // Error + +type Contravariant2 = { // Error + f: (x: T) => void; +} + +type Invariant1 = { // Error + f: (x: T) => T; +} + +type Invariant2 = { // Error + f: (x: T) => T; +} + +// Variance in circular types + +type Foo1 = { // Error + x: T; + f: FooFn1; +} + +type FooFn1 = (foo: Bar1) => void; + +type Bar1 = { + value: Foo1; +} + +type Foo2 = { // Error + x: T; + f: FooFn2; +} + +type FooFn2 = (foo: Bar2) => void; + +type Bar2 = { + value: Foo2; +} + +type Foo3 = { + x: T; + f: FooFn3; +} + +type FooFn3 = (foo: Bar3) => void; + +type Bar3 = { + value: Foo3; +} + +// Wrong modifier usage + +type T20 = T; // Error +type T21 = T; // Error +type T22 = T; // Error +type T23 = T; // Error + +declare function f1(x: T): void; // Error +declare function f2(): T; // Error + +class C { + in a = 0; // Error + out b = 0; // Error +} + +// Interface merging + +interface Baz {} +interface Baz {} + +declare let baz1: Baz; +declare let baz2: Baz; + +baz1 = baz2; // Error +baz2 = baz1; // Error + +// Repro from #44572 + +interface Parent { + child: Child | null; + parent: Parent | null; +} + +interface Child extends Parent { + readonly a: A; + readonly b: B; +} + +function fn(inp: Child) { + const a: Child = inp; +} + +const pu: Parent = { child: { a: 0, b: 0, child: null, parent: null }, parent: null }; +const notString: Parent = pu; // Error + +// Repro from comment in #44572 + +declare class StateNode { + _storedEvent: TEvent; + _action: ActionObject; + _state: StateNode; +} + +interface ActionObject { + exec: (meta: StateNode) => void; +} + +declare function createMachine(action: ActionObject): StateNode; + +declare function interpret(machine: StateNode): void; + +const machine = createMachine({} as any); + +interpret(machine); + +declare const qq: ActionObject<{ type: "PLAY"; value: number }>; + +createMachine<{ type: "PLAY"; value: number } | { type: "RESET" }>(qq); // Error + + +//// [varianceAnnotations.js] +"use strict"; +super_covariant = sub_covariant; +sub_covariant = super_covariant; // Error +super_contravariant = sub_contravariant; // Error +sub_contravariant = super_contravariant; +super_invariant = sub_invariant; // Error +sub_invariant = super_invariant; // Error +var C = /** @class */ (function () { + function C() { + this.a = 0; // Error + this.b = 0; // Error + } + return C; +}()); +baz1 = baz2; // Error +baz2 = baz1; // Error +function fn(inp) { + var a = inp; +} +var pu = { child: { a: 0, b: 0, child: null, parent: null }, parent: null }; +var notString = pu; // Error +var machine = createMachine({}); +interpret(machine); +createMachine(qq); // Error + + +//// [varianceAnnotations.d.ts] +declare type Covariant = { + x: T; +}; +declare let super_covariant: Covariant; +declare let sub_covariant: Covariant; +declare type Contravariant = { + f: (x: T) => void; +}; +declare let super_contravariant: Contravariant; +declare let sub_contravariant: Contravariant; +declare type Invariant = { + f: (x: T) => T; +}; +declare let super_invariant: Invariant; +declare let sub_invariant: Invariant; +declare type T10 = T; +declare type T11 = keyof T; +declare type T12 = T[K]; +declare type T13 = T[keyof T]; +declare type Covariant1 = { + x: T; +}; +declare type Contravariant1 = keyof T; +declare type Contravariant2 = { + f: (x: T) => void; +}; +declare type Invariant1 = { + f: (x: T) => T; +}; +declare type Invariant2 = { + f: (x: T) => T; +}; +declare type Foo1 = { + x: T; + f: FooFn1; +}; +declare type FooFn1 = (foo: Bar1) => void; +declare type Bar1 = { + value: Foo1; +}; +declare type Foo2 = { + x: T; + f: FooFn2; +}; +declare type FooFn2 = (foo: Bar2) => void; +declare type Bar2 = { + value: Foo2; +}; +declare type Foo3 = { + x: T; + f: FooFn3; +}; +declare type FooFn3 = (foo: Bar3) => void; +declare type Bar3 = { + value: Foo3; +}; +declare type T20 = T; +declare type T21 = T; +declare type T22 = T; +declare type T23 = T; +declare function f1(x: T): void; +declare function f2(): T; +declare class C { + in a: number; + out b: number; +} +interface Baz { +} +interface Baz { +} +declare let baz1: Baz; +declare let baz2: Baz; +interface Parent { + child: Child | null; + parent: Parent | null; +} +interface Child extends Parent { + readonly a: A; + readonly b: B; +} +declare function fn(inp: Child): void; +declare const pu: Parent; +declare const notString: Parent; +declare class StateNode { + _storedEvent: TEvent; + _action: ActionObject; + _state: StateNode; +} +interface ActionObject { + exec: (meta: StateNode) => void; +} +declare function createMachine(action: ActionObject): StateNode; +declare function interpret(machine: StateNode): void; +declare const machine: StateNode; +declare const qq: ActionObject<{ + type: "PLAY"; + value: number; +}>; diff --git a/tests/baselines/reference/varianceAnnotations.symbols b/tests/baselines/reference/varianceAnnotations.symbols new file mode 100644 index 00000000000..78a5b9be393 --- /dev/null +++ b/tests/baselines/reference/varianceAnnotations.symbols @@ -0,0 +1,450 @@ +=== tests/cases/conformance/types/typeParameters/typeParameterLists/varianceAnnotations.ts === +type Covariant = { +>Covariant : Symbol(Covariant, Decl(varianceAnnotations.ts, 0, 0)) +>T : Symbol(T, Decl(varianceAnnotations.ts, 0, 15)) + + x: T; +>x : Symbol(x, Decl(varianceAnnotations.ts, 0, 25)) +>T : Symbol(T, Decl(varianceAnnotations.ts, 0, 15)) +} + +declare let super_covariant: Covariant; +>super_covariant : Symbol(super_covariant, Decl(varianceAnnotations.ts, 4, 11)) +>Covariant : Symbol(Covariant, Decl(varianceAnnotations.ts, 0, 0)) + +declare let sub_covariant: Covariant; +>sub_covariant : Symbol(sub_covariant, Decl(varianceAnnotations.ts, 5, 11)) +>Covariant : Symbol(Covariant, Decl(varianceAnnotations.ts, 0, 0)) + +super_covariant = sub_covariant; +>super_covariant : Symbol(super_covariant, Decl(varianceAnnotations.ts, 4, 11)) +>sub_covariant : Symbol(sub_covariant, Decl(varianceAnnotations.ts, 5, 11)) + +sub_covariant = super_covariant; // Error +>sub_covariant : Symbol(sub_covariant, Decl(varianceAnnotations.ts, 5, 11)) +>super_covariant : Symbol(super_covariant, Decl(varianceAnnotations.ts, 4, 11)) + +type Contravariant = { +>Contravariant : Symbol(Contravariant, Decl(varianceAnnotations.ts, 8, 32)) +>T : Symbol(T, Decl(varianceAnnotations.ts, 10, 19)) + + f: (x: T) => void; +>f : Symbol(f, Decl(varianceAnnotations.ts, 10, 28)) +>x : Symbol(x, Decl(varianceAnnotations.ts, 11, 8)) +>T : Symbol(T, Decl(varianceAnnotations.ts, 10, 19)) +} + +declare let super_contravariant: Contravariant; +>super_contravariant : Symbol(super_contravariant, Decl(varianceAnnotations.ts, 14, 11)) +>Contravariant : Symbol(Contravariant, Decl(varianceAnnotations.ts, 8, 32)) + +declare let sub_contravariant: Contravariant; +>sub_contravariant : Symbol(sub_contravariant, Decl(varianceAnnotations.ts, 15, 11)) +>Contravariant : Symbol(Contravariant, Decl(varianceAnnotations.ts, 8, 32)) + +super_contravariant = sub_contravariant; // Error +>super_contravariant : Symbol(super_contravariant, Decl(varianceAnnotations.ts, 14, 11)) +>sub_contravariant : Symbol(sub_contravariant, Decl(varianceAnnotations.ts, 15, 11)) + +sub_contravariant = super_contravariant; +>sub_contravariant : Symbol(sub_contravariant, Decl(varianceAnnotations.ts, 15, 11)) +>super_contravariant : Symbol(super_contravariant, Decl(varianceAnnotations.ts, 14, 11)) + +type Invariant = { +>Invariant : Symbol(Invariant, Decl(varianceAnnotations.ts, 18, 40)) +>T : Symbol(T, Decl(varianceAnnotations.ts, 20, 15)) + + f: (x: T) => T; +>f : Symbol(f, Decl(varianceAnnotations.ts, 20, 28)) +>x : Symbol(x, Decl(varianceAnnotations.ts, 21, 8)) +>T : Symbol(T, Decl(varianceAnnotations.ts, 20, 15)) +>T : Symbol(T, Decl(varianceAnnotations.ts, 20, 15)) +} + +declare let super_invariant: Invariant; +>super_invariant : Symbol(super_invariant, Decl(varianceAnnotations.ts, 24, 11)) +>Invariant : Symbol(Invariant, Decl(varianceAnnotations.ts, 18, 40)) + +declare let sub_invariant: Invariant; +>sub_invariant : Symbol(sub_invariant, Decl(varianceAnnotations.ts, 25, 11)) +>Invariant : Symbol(Invariant, Decl(varianceAnnotations.ts, 18, 40)) + +super_invariant = sub_invariant; // Error +>super_invariant : Symbol(super_invariant, Decl(varianceAnnotations.ts, 24, 11)) +>sub_invariant : Symbol(sub_invariant, Decl(varianceAnnotations.ts, 25, 11)) + +sub_invariant = super_invariant; // Error +>sub_invariant : Symbol(sub_invariant, Decl(varianceAnnotations.ts, 25, 11)) +>super_invariant : Symbol(super_invariant, Decl(varianceAnnotations.ts, 24, 11)) + +// Variance of various type constructors + +type T10 = T; +>T10 : Symbol(T10, Decl(varianceAnnotations.ts, 28, 32)) +>T : Symbol(T, Decl(varianceAnnotations.ts, 32, 9)) +>T : Symbol(T, Decl(varianceAnnotations.ts, 32, 9)) + +type T11 = keyof T; +>T11 : Symbol(T11, Decl(varianceAnnotations.ts, 32, 20)) +>T : Symbol(T, Decl(varianceAnnotations.ts, 33, 9)) +>T : Symbol(T, Decl(varianceAnnotations.ts, 33, 9)) + +type T12 = T[K]; +>T12 : Symbol(T12, Decl(varianceAnnotations.ts, 33, 25)) +>T : Symbol(T, Decl(varianceAnnotations.ts, 34, 9)) +>K : Symbol(K, Decl(varianceAnnotations.ts, 34, 15)) +>T : Symbol(T, Decl(varianceAnnotations.ts, 34, 9)) +>T : Symbol(T, Decl(varianceAnnotations.ts, 34, 9)) +>K : Symbol(K, Decl(varianceAnnotations.ts, 34, 15)) + +type T13 = T[keyof T]; +>T13 : Symbol(T13, Decl(varianceAnnotations.ts, 34, 46)) +>T : Symbol(T, Decl(varianceAnnotations.ts, 35, 9)) +>T : Symbol(T, Decl(varianceAnnotations.ts, 35, 9)) +>T : Symbol(T, Decl(varianceAnnotations.ts, 35, 9)) + +// Variance annotation errors + +type Covariant1 = { // Error +>Covariant1 : Symbol(Covariant1, Decl(varianceAnnotations.ts, 35, 32)) +>T : Symbol(T, Decl(varianceAnnotations.ts, 39, 16)) + + x: T; +>x : Symbol(x, Decl(varianceAnnotations.ts, 39, 25)) +>T : Symbol(T, Decl(varianceAnnotations.ts, 39, 16)) +} + +type Contravariant1 = keyof T; // Error +>Contravariant1 : Symbol(Contravariant1, Decl(varianceAnnotations.ts, 41, 1)) +>T : Symbol(T, Decl(varianceAnnotations.ts, 43, 20)) +>T : Symbol(T, Decl(varianceAnnotations.ts, 43, 20)) + +type Contravariant2 = { // Error +>Contravariant2 : Symbol(Contravariant2, Decl(varianceAnnotations.ts, 43, 37)) +>T : Symbol(T, Decl(varianceAnnotations.ts, 45, 20)) + + f: (x: T) => void; +>f : Symbol(f, Decl(varianceAnnotations.ts, 45, 30)) +>x : Symbol(x, Decl(varianceAnnotations.ts, 46, 8)) +>T : Symbol(T, Decl(varianceAnnotations.ts, 45, 20)) +} + +type Invariant1 = { // Error +>Invariant1 : Symbol(Invariant1, Decl(varianceAnnotations.ts, 47, 1)) +>T : Symbol(T, Decl(varianceAnnotations.ts, 49, 16)) + + f: (x: T) => T; +>f : Symbol(f, Decl(varianceAnnotations.ts, 49, 25)) +>x : Symbol(x, Decl(varianceAnnotations.ts, 50, 8)) +>T : Symbol(T, Decl(varianceAnnotations.ts, 49, 16)) +>T : Symbol(T, Decl(varianceAnnotations.ts, 49, 16)) +} + +type Invariant2 = { // Error +>Invariant2 : Symbol(Invariant2, Decl(varianceAnnotations.ts, 51, 1)) +>T : Symbol(T, Decl(varianceAnnotations.ts, 53, 16)) + + f: (x: T) => T; +>f : Symbol(f, Decl(varianceAnnotations.ts, 53, 26)) +>x : Symbol(x, Decl(varianceAnnotations.ts, 54, 8)) +>T : Symbol(T, Decl(varianceAnnotations.ts, 53, 16)) +>T : Symbol(T, Decl(varianceAnnotations.ts, 53, 16)) +} + +// Variance in circular types + +type Foo1 = { // Error +>Foo1 : Symbol(Foo1, Decl(varianceAnnotations.ts, 55, 1)) +>T : Symbol(T, Decl(varianceAnnotations.ts, 59, 10)) + + x: T; +>x : Symbol(x, Decl(varianceAnnotations.ts, 59, 19)) +>T : Symbol(T, Decl(varianceAnnotations.ts, 59, 10)) + + f: FooFn1; +>f : Symbol(f, Decl(varianceAnnotations.ts, 60, 9)) +>FooFn1 : Symbol(FooFn1, Decl(varianceAnnotations.ts, 62, 1)) +>T : Symbol(T, Decl(varianceAnnotations.ts, 59, 10)) +} + +type FooFn1 = (foo: Bar1) => void; +>FooFn1 : Symbol(FooFn1, Decl(varianceAnnotations.ts, 62, 1)) +>T : Symbol(T, Decl(varianceAnnotations.ts, 64, 12)) +>foo : Symbol(foo, Decl(varianceAnnotations.ts, 64, 18)) +>Bar1 : Symbol(Bar1, Decl(varianceAnnotations.ts, 64, 42)) +>T : Symbol(T, Decl(varianceAnnotations.ts, 64, 12)) + +type Bar1 = { +>Bar1 : Symbol(Bar1, Decl(varianceAnnotations.ts, 64, 42)) +>T : Symbol(T, Decl(varianceAnnotations.ts, 66, 10)) + + value: Foo1; +>value : Symbol(value, Decl(varianceAnnotations.ts, 66, 16)) +>Foo1 : Symbol(Foo1, Decl(varianceAnnotations.ts, 55, 1)) +>T : Symbol(T, Decl(varianceAnnotations.ts, 66, 10)) +} + +type Foo2 = { // Error +>Foo2 : Symbol(Foo2, Decl(varianceAnnotations.ts, 68, 1)) +>T : Symbol(T, Decl(varianceAnnotations.ts, 70, 10)) + + x: T; +>x : Symbol(x, Decl(varianceAnnotations.ts, 70, 20)) +>T : Symbol(T, Decl(varianceAnnotations.ts, 70, 10)) + + f: FooFn2; +>f : Symbol(f, Decl(varianceAnnotations.ts, 71, 9)) +>FooFn2 : Symbol(FooFn2, Decl(varianceAnnotations.ts, 73, 1)) +>T : Symbol(T, Decl(varianceAnnotations.ts, 70, 10)) +} + +type FooFn2 = (foo: Bar2) => void; +>FooFn2 : Symbol(FooFn2, Decl(varianceAnnotations.ts, 73, 1)) +>T : Symbol(T, Decl(varianceAnnotations.ts, 75, 12)) +>foo : Symbol(foo, Decl(varianceAnnotations.ts, 75, 18)) +>Bar2 : Symbol(Bar2, Decl(varianceAnnotations.ts, 75, 42)) +>T : Symbol(T, Decl(varianceAnnotations.ts, 75, 12)) + +type Bar2 = { +>Bar2 : Symbol(Bar2, Decl(varianceAnnotations.ts, 75, 42)) +>T : Symbol(T, Decl(varianceAnnotations.ts, 77, 10)) + + value: Foo2; +>value : Symbol(value, Decl(varianceAnnotations.ts, 77, 16)) +>Foo2 : Symbol(Foo2, Decl(varianceAnnotations.ts, 68, 1)) +>T : Symbol(T, Decl(varianceAnnotations.ts, 77, 10)) +} + +type Foo3 = { +>Foo3 : Symbol(Foo3, Decl(varianceAnnotations.ts, 79, 1)) +>T : Symbol(T, Decl(varianceAnnotations.ts, 81, 10)) + + x: T; +>x : Symbol(x, Decl(varianceAnnotations.ts, 81, 23)) +>T : Symbol(T, Decl(varianceAnnotations.ts, 81, 10)) + + f: FooFn3; +>f : Symbol(f, Decl(varianceAnnotations.ts, 82, 9)) +>FooFn3 : Symbol(FooFn3, Decl(varianceAnnotations.ts, 84, 1)) +>T : Symbol(T, Decl(varianceAnnotations.ts, 81, 10)) +} + +type FooFn3 = (foo: Bar3) => void; +>FooFn3 : Symbol(FooFn3, Decl(varianceAnnotations.ts, 84, 1)) +>T : Symbol(T, Decl(varianceAnnotations.ts, 86, 12)) +>foo : Symbol(foo, Decl(varianceAnnotations.ts, 86, 18)) +>Bar3 : Symbol(Bar3, Decl(varianceAnnotations.ts, 86, 42)) +>T : Symbol(T, Decl(varianceAnnotations.ts, 86, 12)) + +type Bar3 = { +>Bar3 : Symbol(Bar3, Decl(varianceAnnotations.ts, 86, 42)) +>T : Symbol(T, Decl(varianceAnnotations.ts, 88, 10)) + + value: Foo3; +>value : Symbol(value, Decl(varianceAnnotations.ts, 88, 16)) +>Foo3 : Symbol(Foo3, Decl(varianceAnnotations.ts, 79, 1)) +>T : Symbol(T, Decl(varianceAnnotations.ts, 88, 10)) +} + +// Wrong modifier usage + +type T20 = T; // Error +>T20 : Symbol(T20, Decl(varianceAnnotations.ts, 90, 1)) +>T : Symbol(T, Decl(varianceAnnotations.ts, 94, 9)) +>T : Symbol(T, Decl(varianceAnnotations.ts, 94, 9)) + +type T21 = T; // Error +>T21 : Symbol(T21, Decl(varianceAnnotations.ts, 94, 23)) +>T : Symbol(T, Decl(varianceAnnotations.ts, 95, 9)) +>T : Symbol(T, Decl(varianceAnnotations.ts, 95, 9)) + +type T22 = T; // Error +>T22 : Symbol(T22, Decl(varianceAnnotations.ts, 95, 26)) +>T : Symbol(T, Decl(varianceAnnotations.ts, 96, 9)) +>T : Symbol(T, Decl(varianceAnnotations.ts, 96, 9)) + +type T23 = T; // Error +>T23 : Symbol(T23, Decl(varianceAnnotations.ts, 96, 27)) +>T : Symbol(T, Decl(varianceAnnotations.ts, 97, 9)) +>T : Symbol(T, Decl(varianceAnnotations.ts, 97, 9)) + +declare function f1(x: T): void; // Error +>f1 : Symbol(f1, Decl(varianceAnnotations.ts, 97, 23)) +>T : Symbol(T, Decl(varianceAnnotations.ts, 99, 20)) +>x : Symbol(x, Decl(varianceAnnotations.ts, 99, 26)) +>T : Symbol(T, Decl(varianceAnnotations.ts, 99, 20)) + +declare function f2(): T; // Error +>f2 : Symbol(f2, Decl(varianceAnnotations.ts, 99, 38)) +>T : Symbol(T, Decl(varianceAnnotations.ts, 100, 20)) +>T : Symbol(T, Decl(varianceAnnotations.ts, 100, 20)) + +class C { +>C : Symbol(C, Decl(varianceAnnotations.ts, 100, 32)) + + in a = 0; // Error +>a : Symbol(C.a, Decl(varianceAnnotations.ts, 102, 9)) + + out b = 0; // Error +>b : Symbol(C.b, Decl(varianceAnnotations.ts, 103, 13)) +} + +// Interface merging + +interface Baz {} +>Baz : Symbol(Baz, Decl(varianceAnnotations.ts, 105, 1), Decl(varianceAnnotations.ts, 109, 23)) +>T : Symbol(T, Decl(varianceAnnotations.ts, 109, 14), Decl(varianceAnnotations.ts, 110, 14)) + +interface Baz {} +>Baz : Symbol(Baz, Decl(varianceAnnotations.ts, 105, 1), Decl(varianceAnnotations.ts, 109, 23)) +>T : Symbol(T, Decl(varianceAnnotations.ts, 109, 14), Decl(varianceAnnotations.ts, 110, 14)) + +declare let baz1: Baz; +>baz1 : Symbol(baz1, Decl(varianceAnnotations.ts, 112, 11)) +>Baz : Symbol(Baz, Decl(varianceAnnotations.ts, 105, 1), Decl(varianceAnnotations.ts, 109, 23)) + +declare let baz2: Baz; +>baz2 : Symbol(baz2, Decl(varianceAnnotations.ts, 113, 11)) +>Baz : Symbol(Baz, Decl(varianceAnnotations.ts, 105, 1), Decl(varianceAnnotations.ts, 109, 23)) + +baz1 = baz2; // Error +>baz1 : Symbol(baz1, Decl(varianceAnnotations.ts, 112, 11)) +>baz2 : Symbol(baz2, Decl(varianceAnnotations.ts, 113, 11)) + +baz2 = baz1; // Error +>baz2 : Symbol(baz2, Decl(varianceAnnotations.ts, 113, 11)) +>baz1 : Symbol(baz1, Decl(varianceAnnotations.ts, 112, 11)) + +// Repro from #44572 + +interface Parent { +>Parent : Symbol(Parent, Decl(varianceAnnotations.ts, 116, 12)) +>A : Symbol(A, Decl(varianceAnnotations.ts, 120, 17)) + + child: Child | null; +>child : Symbol(Parent.child, Decl(varianceAnnotations.ts, 120, 25)) +>Child : Symbol(Child, Decl(varianceAnnotations.ts, 123, 1)) +>A : Symbol(A, Decl(varianceAnnotations.ts, 120, 17)) + + parent: Parent | null; +>parent : Symbol(Parent.parent, Decl(varianceAnnotations.ts, 121, 27)) +>Parent : Symbol(Parent, Decl(varianceAnnotations.ts, 116, 12)) +>A : Symbol(A, Decl(varianceAnnotations.ts, 120, 17)) +} + +interface Child extends Parent { +>Child : Symbol(Child, Decl(varianceAnnotations.ts, 123, 1)) +>A : Symbol(A, Decl(varianceAnnotations.ts, 125, 16)) +>B : Symbol(B, Decl(varianceAnnotations.ts, 125, 18)) +>Parent : Symbol(Parent, Decl(varianceAnnotations.ts, 116, 12)) +>A : Symbol(A, Decl(varianceAnnotations.ts, 125, 16)) + + readonly a: A; +>a : Symbol(Child.a, Decl(varianceAnnotations.ts, 125, 51)) +>A : Symbol(A, Decl(varianceAnnotations.ts, 125, 16)) + + readonly b: B; +>b : Symbol(Child.b, Decl(varianceAnnotations.ts, 126, 18)) +>B : Symbol(B, Decl(varianceAnnotations.ts, 125, 18)) +} + +function fn(inp: Child) { +>fn : Symbol(fn, Decl(varianceAnnotations.ts, 128, 1)) +>A : Symbol(A, Decl(varianceAnnotations.ts, 130, 12)) +>inp : Symbol(inp, Decl(varianceAnnotations.ts, 130, 15)) +>Child : Symbol(Child, Decl(varianceAnnotations.ts, 123, 1)) +>A : Symbol(A, Decl(varianceAnnotations.ts, 130, 12)) + + const a: Child = inp; +>a : Symbol(a, Decl(varianceAnnotations.ts, 131, 9)) +>Child : Symbol(Child, Decl(varianceAnnotations.ts, 123, 1)) +>inp : Symbol(inp, Decl(varianceAnnotations.ts, 130, 15)) +} + +const pu: Parent = { child: { a: 0, b: 0, child: null, parent: null }, parent: null }; +>pu : Symbol(pu, Decl(varianceAnnotations.ts, 134, 5)) +>Parent : Symbol(Parent, Decl(varianceAnnotations.ts, 116, 12)) +>child : Symbol(child, Decl(varianceAnnotations.ts, 134, 29)) +>a : Symbol(a, Decl(varianceAnnotations.ts, 134, 38)) +>b : Symbol(b, Decl(varianceAnnotations.ts, 134, 44)) +>child : Symbol(child, Decl(varianceAnnotations.ts, 134, 50)) +>parent : Symbol(parent, Decl(varianceAnnotations.ts, 134, 63)) +>parent : Symbol(parent, Decl(varianceAnnotations.ts, 134, 79)) + +const notString: Parent = pu; // Error +>notString : Symbol(notString, Decl(varianceAnnotations.ts, 135, 5)) +>Parent : Symbol(Parent, Decl(varianceAnnotations.ts, 116, 12)) +>pu : Symbol(pu, Decl(varianceAnnotations.ts, 134, 5)) + +// Repro from comment in #44572 + +declare class StateNode { +>StateNode : Symbol(StateNode, Decl(varianceAnnotations.ts, 135, 37)) +>TContext : Symbol(TContext, Decl(varianceAnnotations.ts, 139, 24)) +>TEvent : Symbol(TEvent, Decl(varianceAnnotations.ts, 139, 33)) +>type : Symbol(type, Decl(varianceAnnotations.ts, 139, 57)) + + _storedEvent: TEvent; +>_storedEvent : Symbol(StateNode._storedEvent, Decl(varianceAnnotations.ts, 139, 75)) +>TEvent : Symbol(TEvent, Decl(varianceAnnotations.ts, 139, 33)) + + _action: ActionObject; +>_action : Symbol(StateNode._action, Decl(varianceAnnotations.ts, 140, 25)) +>ActionObject : Symbol(ActionObject, Decl(varianceAnnotations.ts, 143, 1)) +>TEvent : Symbol(TEvent, Decl(varianceAnnotations.ts, 139, 33)) + + _state: StateNode; +>_state : Symbol(StateNode._state, Decl(varianceAnnotations.ts, 141, 34)) +>StateNode : Symbol(StateNode, Decl(varianceAnnotations.ts, 135, 37)) +>TContext : Symbol(TContext, Decl(varianceAnnotations.ts, 139, 24)) +} + +interface ActionObject { +>ActionObject : Symbol(ActionObject, Decl(varianceAnnotations.ts, 143, 1)) +>TEvent : Symbol(TEvent, Decl(varianceAnnotations.ts, 145, 23)) +>type : Symbol(type, Decl(varianceAnnotations.ts, 145, 39)) + + exec: (meta: StateNode) => void; +>exec : Symbol(ActionObject.exec, Decl(varianceAnnotations.ts, 145, 57)) +>meta : Symbol(meta, Decl(varianceAnnotations.ts, 146, 11)) +>StateNode : Symbol(StateNode, Decl(varianceAnnotations.ts, 135, 37)) +>TEvent : Symbol(TEvent, Decl(varianceAnnotations.ts, 145, 23)) +} + +declare function createMachine(action: ActionObject): StateNode; +>createMachine : Symbol(createMachine, Decl(varianceAnnotations.ts, 147, 1)) +>TEvent : Symbol(TEvent, Decl(varianceAnnotations.ts, 149, 31)) +>type : Symbol(type, Decl(varianceAnnotations.ts, 149, 47)) +>action : Symbol(action, Decl(varianceAnnotations.ts, 149, 64)) +>ActionObject : Symbol(ActionObject, Decl(varianceAnnotations.ts, 143, 1)) +>TEvent : Symbol(TEvent, Decl(varianceAnnotations.ts, 149, 31)) +>StateNode : Symbol(StateNode, Decl(varianceAnnotations.ts, 135, 37)) + +declare function interpret(machine: StateNode): void; +>interpret : Symbol(interpret, Decl(varianceAnnotations.ts, 149, 115)) +>TContext : Symbol(TContext, Decl(varianceAnnotations.ts, 151, 27)) +>machine : Symbol(machine, Decl(varianceAnnotations.ts, 151, 37)) +>StateNode : Symbol(StateNode, Decl(varianceAnnotations.ts, 135, 37)) +>TContext : Symbol(TContext, Decl(varianceAnnotations.ts, 151, 27)) + +const machine = createMachine({} as any); +>machine : Symbol(machine, Decl(varianceAnnotations.ts, 153, 5)) +>createMachine : Symbol(createMachine, Decl(varianceAnnotations.ts, 147, 1)) + +interpret(machine); +>interpret : Symbol(interpret, Decl(varianceAnnotations.ts, 149, 115)) +>machine : Symbol(machine, Decl(varianceAnnotations.ts, 153, 5)) + +declare const qq: ActionObject<{ type: "PLAY"; value: number }>; +>qq : Symbol(qq, Decl(varianceAnnotations.ts, 157, 13)) +>ActionObject : Symbol(ActionObject, Decl(varianceAnnotations.ts, 143, 1)) +>type : Symbol(type, Decl(varianceAnnotations.ts, 157, 32)) +>value : Symbol(value, Decl(varianceAnnotations.ts, 157, 46)) + +createMachine<{ type: "PLAY"; value: number } | { type: "RESET" }>(qq); // Error +>createMachine : Symbol(createMachine, Decl(varianceAnnotations.ts, 147, 1)) +>type : Symbol(type, Decl(varianceAnnotations.ts, 159, 15)) +>value : Symbol(value, Decl(varianceAnnotations.ts, 159, 29)) +>type : Symbol(type, Decl(varianceAnnotations.ts, 159, 49)) +>qq : Symbol(qq, Decl(varianceAnnotations.ts, 157, 13)) + diff --git a/tests/baselines/reference/varianceAnnotations.types b/tests/baselines/reference/varianceAnnotations.types new file mode 100644 index 00000000000..e584d60a696 --- /dev/null +++ b/tests/baselines/reference/varianceAnnotations.types @@ -0,0 +1,348 @@ +=== tests/cases/conformance/types/typeParameters/typeParameterLists/varianceAnnotations.ts === +type Covariant = { +>Covariant : Covariant + + x: T; +>x : T +} + +declare let super_covariant: Covariant; +>super_covariant : Covariant + +declare let sub_covariant: Covariant; +>sub_covariant : Covariant + +super_covariant = sub_covariant; +>super_covariant = sub_covariant : Covariant +>super_covariant : Covariant +>sub_covariant : Covariant + +sub_covariant = super_covariant; // Error +>sub_covariant = super_covariant : Covariant +>sub_covariant : Covariant +>super_covariant : Covariant + +type Contravariant = { +>Contravariant : Contravariant + + f: (x: T) => void; +>f : (x: T) => void +>x : T +} + +declare let super_contravariant: Contravariant; +>super_contravariant : Contravariant + +declare let sub_contravariant: Contravariant; +>sub_contravariant : Contravariant + +super_contravariant = sub_contravariant; // Error +>super_contravariant = sub_contravariant : Contravariant +>super_contravariant : Contravariant +>sub_contravariant : Contravariant + +sub_contravariant = super_contravariant; +>sub_contravariant = super_contravariant : Contravariant +>sub_contravariant : Contravariant +>super_contravariant : Contravariant + +type Invariant = { +>Invariant : Invariant + + f: (x: T) => T; +>f : (x: T) => T +>x : T +} + +declare let super_invariant: Invariant; +>super_invariant : Invariant + +declare let sub_invariant: Invariant; +>sub_invariant : Invariant + +super_invariant = sub_invariant; // Error +>super_invariant = sub_invariant : Invariant +>super_invariant : Invariant +>sub_invariant : Invariant + +sub_invariant = super_invariant; // Error +>sub_invariant = super_invariant : Invariant +>sub_invariant : Invariant +>super_invariant : Invariant + +// Variance of various type constructors + +type T10 = T; +>T10 : T + +type T11 = keyof T; +>T11 : keyof T + +type T12 = T[K]; +>T12 : T12 + +type T13 = T[keyof T]; +>T13 : T13 + +// Variance annotation errors + +type Covariant1 = { // Error +>Covariant1 : Covariant1 + + x: T; +>x : T +} + +type Contravariant1 = keyof T; // Error +>Contravariant1 : keyof T + +type Contravariant2 = { // Error +>Contravariant2 : Contravariant2 + + f: (x: T) => void; +>f : (x: T) => void +>x : T +} + +type Invariant1 = { // Error +>Invariant1 : Invariant1 + + f: (x: T) => T; +>f : (x: T) => T +>x : T +} + +type Invariant2 = { // Error +>Invariant2 : Invariant2 + + f: (x: T) => T; +>f : (x: T) => T +>x : T +} + +// Variance in circular types + +type Foo1 = { // Error +>Foo1 : Foo1 + + x: T; +>x : T + + f: FooFn1; +>f : FooFn1 +} + +type FooFn1 = (foo: Bar1) => void; +>FooFn1 : FooFn1 +>foo : Bar1 + +type Bar1 = { +>Bar1 : Bar1 + + value: Foo1; +>value : Foo1 +} + +type Foo2 = { // Error +>Foo2 : Foo2 + + x: T; +>x : T + + f: FooFn2; +>f : FooFn2 +} + +type FooFn2 = (foo: Bar2) => void; +>FooFn2 : FooFn2 +>foo : Bar2 + +type Bar2 = { +>Bar2 : Bar2 + + value: Foo2; +>value : Foo2 +} + +type Foo3 = { +>Foo3 : Foo3 + + x: T; +>x : T + + f: FooFn3; +>f : FooFn3 +} + +type FooFn3 = (foo: Bar3) => void; +>FooFn3 : FooFn3 +>foo : Bar3 + +type Bar3 = { +>Bar3 : Bar3 + + value: Foo3; +>value : Foo3 +} + +// Wrong modifier usage + +type T20 = T; // Error +>T20 : T + +type T21 = T; // Error +>T21 : T + +type T22 = T; // Error +>T22 : T + +type T23 = T; // Error +>T23 : T + +declare function f1(x: T): void; // Error +>f1 : (x: T) => void +>x : T + +declare function f2(): T; // Error +>f2 : () => T + +class C { +>C : C + + in a = 0; // Error +>a : number +>0 : 0 + + out b = 0; // Error +>b : number +>0 : 0 +} + +// Interface merging + +interface Baz {} +interface Baz {} + +declare let baz1: Baz; +>baz1 : Baz + +declare let baz2: Baz; +>baz2 : Baz + +baz1 = baz2; // Error +>baz1 = baz2 : Baz +>baz1 : Baz +>baz2 : Baz + +baz2 = baz1; // Error +>baz2 = baz1 : Baz +>baz2 : Baz +>baz1 : Baz + +// Repro from #44572 + +interface Parent { + child: Child | null; +>child : Child | null +>null : null + + parent: Parent | null; +>parent : Parent | null +>null : null +} + +interface Child extends Parent { + readonly a: A; +>a : A + + readonly b: B; +>b : B +} + +function fn(inp: Child) { +>fn : (inp: Child) => void +>inp : Child + + const a: Child = inp; +>a : Child +>inp : Child +} + +const pu: Parent = { child: { a: 0, b: 0, child: null, parent: null }, parent: null }; +>pu : Parent +>{ child: { a: 0, b: 0, child: null, parent: null }, parent: null } : { child: { a: number; b: number; child: null; parent: null; }; parent: null; } +>child : { a: number; b: number; child: null; parent: null; } +>{ a: 0, b: 0, child: null, parent: null } : { a: number; b: number; child: null; parent: null; } +>a : number +>0 : 0 +>b : number +>0 : 0 +>child : null +>null : null +>parent : null +>null : null +>parent : null +>null : null + +const notString: Parent = pu; // Error +>notString : Parent +>pu : Parent + +// Repro from comment in #44572 + +declare class StateNode { +>StateNode : StateNode +>type : string + + _storedEvent: TEvent; +>_storedEvent : TEvent + + _action: ActionObject; +>_action : ActionObject + + _state: StateNode; +>_state : StateNode +} + +interface ActionObject { +>type : string + + exec: (meta: StateNode) => void; +>exec : (meta: StateNode) => void +>meta : StateNode +} + +declare function createMachine(action: ActionObject): StateNode; +>createMachine : (action: ActionObject) => StateNode +>type : string +>action : ActionObject + +declare function interpret(machine: StateNode): void; +>interpret : (machine: StateNode) => void +>machine : StateNode + +const machine = createMachine({} as any); +>machine : StateNode +>createMachine({} as any) : StateNode +>createMachine : (action: ActionObject) => StateNode +>{} as any : any +>{} : {} + +interpret(machine); +>interpret(machine) : void +>interpret : (machine: StateNode) => void +>machine : StateNode + +declare const qq: ActionObject<{ type: "PLAY"; value: number }>; +>qq : ActionObject<{ type: "PLAY"; value: number; }> +>type : "PLAY" +>value : number + +createMachine<{ type: "PLAY"; value: number } | { type: "RESET" }>(qq); // Error +>createMachine<{ type: "PLAY"; value: number } | { type: "RESET" }>(qq) : StateNode +>createMachine : (action: ActionObject) => StateNode +>type : "PLAY" +>value : number +>type : "RESET" +>qq : ActionObject<{ type: "PLAY"; value: number; }> + diff --git a/tests/cases/compiler/circularAccessorAnnotations.ts b/tests/cases/compiler/circularAccessorAnnotations.ts new file mode 100644 index 00000000000..0f6908bff81 --- /dev/null +++ b/tests/cases/compiler/circularAccessorAnnotations.ts @@ -0,0 +1,28 @@ +// @strict: true +// @declaration: true + +declare const c1: { + get foo(): typeof c1.foo; +} + +declare const c2: { + set foo(value: typeof c2.foo); +} + +declare const c3: { + get foo(): string; + set foo(value: typeof c3.foo); +} + +type T1 = { + get foo(): T1["foo"]; +} + +type T2 = { + set foo(value: T2["foo"]); +} + +type T3 = { + get foo(): string; + set foo(value: T3["foo"]); +} diff --git a/tests/cases/compiler/circularGetAccessor.ts b/tests/cases/compiler/circularGetAccessor.ts new file mode 100644 index 00000000000..b50bc7fc680 --- /dev/null +++ b/tests/cases/compiler/circularGetAccessor.ts @@ -0,0 +1,5 @@ +// @noImplicitAny: true, false + +declare class C { + get foo(): typeof this.foo; +} diff --git a/tests/cases/compiler/discriminantPropertyInference.ts b/tests/cases/compiler/discriminantPropertyInference.ts index e2b39488b21..5aeb0dd0c0d 100644 --- a/tests/cases/compiler/discriminantPropertyInference.ts +++ b/tests/cases/compiler/discriminantPropertyInference.ts @@ -13,9 +13,7 @@ type DiscriminatorFalse = { cb: (x: number) => void; } -type Unrelated = { - val: number; -} +type Props = DiscriminatorTrue | DiscriminatorFalse; declare function f(options: DiscriminatorTrue | DiscriminatorFalse): any; @@ -41,11 +39,3 @@ f({ f({ cb: n => n.toFixed() }); - - -declare function g(options: DiscriminatorTrue | DiscriminatorFalse | Unrelated): any; - -// requires checking properties of all types, rather than properties of just the union type (e.g. only intersection) -g({ - cb: n => n.toFixed() -}); diff --git a/tests/cases/compiler/emitDecoratorMetadata_isolatedModules.ts b/tests/cases/compiler/emitDecoratorMetadata_isolatedModules.ts new file mode 100644 index 00000000000..e90af623cc1 --- /dev/null +++ b/tests/cases/compiler/emitDecoratorMetadata_isolatedModules.ts @@ -0,0 +1,41 @@ +// @experimentalDecorators: true +// @emitDecoratorMetadata: true +// @isolatedModules: true +// @module: commonjs,esnext + +// @Filename: type1.ts +interface T1 {} +export type { T1 } + +// @Filename: type2.ts +export interface T2 {} + +// @Filename: class3.ts +export class C3 {} + +// @Filename: index.ts +import { T1 } from "./type1"; +import * as t1 from "./type1"; +import type { T2 } from "./type2"; +import { C3 } from "./class3"; +declare var EventListener: any; + +class HelloWorld { + @EventListener('1') + handleEvent1(event: T1) {} // Error + + @EventListener('2') + handleEvent2(event: T2) {} // Ok + + @EventListener('1') + p1!: T1; // Error + + @EventListener('1') + p1_ns!: t1.T1; // Ok + + @EventListener('2') + p2!: T2; // Ok + + @EventListener('3') + handleEvent3(event: C3): T1 { return undefined! } // Ok, Error +} diff --git a/tests/cases/compiler/genericUnboundedTypeParamAssignability.ts b/tests/cases/compiler/genericUnboundedTypeParamAssignability.ts new file mode 100644 index 00000000000..542e96753ff --- /dev/null +++ b/tests/cases/compiler/genericUnboundedTypeParamAssignability.ts @@ -0,0 +1,20 @@ +// @strict: true + +function f1(o: T) { + o.toString(); // error +} + +function f2(o: T) { + o.toString(); // no error +} + +function f3>(o: T) { + o.toString(); // no error +} + +function user(t: T) { + f1(t); + f2(t); // error in strict, unbounded T doesn't satisfy the constraint + f3(t); // error in strict, unbounded T doesn't satisfy the constraint + t.toString(); // error, for the same reason as f1() +} diff --git a/tests/cases/compiler/noParameterReassignmentIIFEAnnotated.ts b/tests/cases/compiler/noParameterReassignmentIIFEAnnotated.ts new file mode 100644 index 00000000000..d634092a15d --- /dev/null +++ b/tests/cases/compiler/noParameterReassignmentIIFEAnnotated.ts @@ -0,0 +1,12 @@ +// @allowJs: true +// @checkJs: true +// @noEmit: true +// @filename: index.js +self.importScripts = (function (importScripts) { + /** + * @param {...unknown} rest + */ + return function () { + return importScripts.apply(this, arguments); + }; +})(importScripts); diff --git a/tests/cases/compiler/noParameterReassignmentJSIIFE.ts b/tests/cases/compiler/noParameterReassignmentJSIIFE.ts new file mode 100644 index 00000000000..175e87887ec --- /dev/null +++ b/tests/cases/compiler/noParameterReassignmentJSIIFE.ts @@ -0,0 +1,9 @@ +// @allowJs: true +// @checkJs: true +// @noEmit: true +// @filename: index.js +self.importScripts = (function (importScripts) { + return function () { + return importScripts.apply(this, arguments); + }; +})(importScripts); diff --git a/tests/cases/compiler/templateLiteralIntersection.ts b/tests/cases/compiler/templateLiteralIntersection.ts new file mode 100644 index 00000000000..9a17d16bc2b --- /dev/null +++ b/tests/cases/compiler/templateLiteralIntersection.ts @@ -0,0 +1,28 @@ +// https://github.com/microsoft/TypeScript/issues/48034 +const a = 'a' + +type A = typeof a +type MixA = A & {foo: string} + +type OriginA1 = `${A}` +type OriginA2 = `${MixA}` + +type B = `${typeof a}` +type MixB = B & { foo: string } + +type OriginB1 = `${B}` +type OriginB2 = `${MixB}` + +type MixC = { foo: string } & A + +type OriginC = `${MixC}` + +type MixD = + `${T & { foo: string }}` +type OriginD = `${MixD & { foo: string }}`; + +type E = `${A & {}}`; +type MixE = E & {} +type OriginE = `${MixE}` + +type OriginF = `${A}foo${A}`; \ No newline at end of file diff --git a/tests/cases/compiler/truthinessCallExpressionCoercion4.ts b/tests/cases/compiler/truthinessCallExpressionCoercion4.ts new file mode 100644 index 00000000000..f585d7b78d1 --- /dev/null +++ b/tests/cases/compiler/truthinessCallExpressionCoercion4.ts @@ -0,0 +1,11 @@ +// @checkJs: true +// @allowJs: true +// @strict: true +// @noEmit: true +// @filename: a.js + +function fn() {} + +if (typeof module === 'object' && module.exports) { + module.exports = fn; +} diff --git a/tests/cases/compiler/tsxDiscriminantPropertyInference.tsx b/tests/cases/compiler/tsxDiscriminantPropertyInference.tsx index d4fe3baf378..d4db0f82d50 100644 --- a/tests/cases/compiler/tsxDiscriminantPropertyInference.tsx +++ b/tests/cases/compiler/tsxDiscriminantPropertyInference.tsx @@ -17,15 +17,9 @@ type DiscriminatorFalse = { cb: (x: number) => void; } -type Unrelated = { - val: number; -} - type Props = DiscriminatorTrue | DiscriminatorFalse; -type UnrelatedProps = Props | Unrelated; - -declare function Comp(props: Props): JSX.Element; +declare function Comp(props: DiscriminatorTrue | DiscriminatorFalse): JSX.Element; // simple inference void ( parseInt(s)} />); @@ -38,8 +32,3 @@ void ( n.toFixed()} />); // requires checking type information since discriminator is missing from object void ( n.toFixed()} />); - -declare function UnrelatedComp(props: UnrelatedProps): JSX.Element; - -// requires checking properties of all types, rather than properties of just the union type (e.g. only intersection) -void ( n.toFixed()} />); diff --git a/tests/cases/conformance/classes/classStaticBlock/classStaticBlock28.ts b/tests/cases/conformance/classes/classStaticBlock/classStaticBlock28.ts new file mode 100644 index 00000000000..90cbf78bfdd --- /dev/null +++ b/tests/cases/conformance/classes/classStaticBlock/classStaticBlock28.ts @@ -0,0 +1,11 @@ +// @strict: true + +let foo: number; + +class C { + static { + foo = 1 + } +} + +console.log(foo) \ No newline at end of file diff --git a/tests/cases/conformance/classes/classStaticBlock/classStaticBlockUseBeforeDef3.ts b/tests/cases/conformance/classes/classStaticBlock/classStaticBlockUseBeforeDef3.ts new file mode 100644 index 00000000000..bf59cb8a8c4 --- /dev/null +++ b/tests/cases/conformance/classes/classStaticBlock/classStaticBlockUseBeforeDef3.ts @@ -0,0 +1,45 @@ +// @noEmit: true +// @strict: true + +class A { + static { + A.doSomething(); // should not error + } + + static doSomething() { + console.log("gotcha!"); + } +} + + +class Baz { + static { + console.log(FOO); // should error + } +} + +const FOO = "FOO"; +class Bar { + static { + console.log(FOO); // should not error + } +} + +let u = "FOO" as "FOO" | "BAR"; + +class CFA { + static { + u = "BAR"; + u; // should be "BAR" + } + + static t = 1; + + static doSomething() {} + + static { + u; // should be "BAR" + } +} + +u; // should be "BAR" diff --git a/tests/cases/conformance/externalModules/typeOnly/exportSpecifiers_js.ts b/tests/cases/conformance/externalModules/typeOnly/exportSpecifiers_js.ts new file mode 100644 index 00000000000..b8280ae66a5 --- /dev/null +++ b/tests/cases/conformance/externalModules/typeOnly/exportSpecifiers_js.ts @@ -0,0 +1,7 @@ +// @allowJs: true +// @checkJs: true +// @noEmit: true + +// @Filename: ./a.js +const foo = 0; +export { type foo }; diff --git a/tests/cases/conformance/externalModules/typeOnly/importSpecifiers_js.ts b/tests/cases/conformance/externalModules/typeOnly/importSpecifiers_js.ts new file mode 100644 index 00000000000..e2c2d8411f2 --- /dev/null +++ b/tests/cases/conformance/externalModules/typeOnly/importSpecifiers_js.ts @@ -0,0 +1,9 @@ +// @allowJs: true +// @checkJs: true +// @noEmit: true + +// @Filename: ./a.ts +export interface A {} + +// @Filename: ./a.js +import { type A } from "./a"; diff --git a/tests/cases/conformance/salsa/plainJSGrammarErrors2.ts b/tests/cases/conformance/salsa/plainJSGrammarErrors2.ts new file mode 100644 index 00000000000..73dfb48001e --- /dev/null +++ b/tests/cases/conformance/salsa/plainJSGrammarErrors2.ts @@ -0,0 +1,14 @@ +// @outdir: out/ +// @target: esnext +// @module: esnext +// @allowJs: true +// @filename: plainJSGrammarErrors2.js + +// @filename: /a.js +export default 1; + +// @filename: /b.js +/** + * @deprecated + */ +export { default as A } from "./a"; diff --git a/tests/cases/conformance/types/mapped/isomorphicMappedTypeInference.ts b/tests/cases/conformance/types/mapped/isomorphicMappedTypeInference.ts index 031cf840d33..4cc2d08be6c 100644 --- a/tests/cases/conformance/types/mapped/isomorphicMappedTypeInference.ts +++ b/tests/cases/conformance/types/mapped/isomorphicMappedTypeInference.ts @@ -26,7 +26,7 @@ function boxify(obj: T): Boxified { return result; } -function unboxify(obj: Boxified): T { +function unboxify(obj: Boxified): T { let result = {} as T; for (let k in obj) { result[k] = unbox(obj[k]); diff --git a/tests/cases/conformance/types/typeParameters/typeParameterLists/varianceAnnotations.ts b/tests/cases/conformance/types/typeParameters/typeParameterLists/varianceAnnotations.ts new file mode 100644 index 00000000000..1a75b0c97a4 --- /dev/null +++ b/tests/cases/conformance/types/typeParameters/typeParameterLists/varianceAnnotations.ts @@ -0,0 +1,163 @@ +// @strict: true +// @declaration: true + +type Covariant = { + x: T; +} + +declare let super_covariant: Covariant; +declare let sub_covariant: Covariant; + +super_covariant = sub_covariant; +sub_covariant = super_covariant; // Error + +type Contravariant = { + f: (x: T) => void; +} + +declare let super_contravariant: Contravariant; +declare let sub_contravariant: Contravariant; + +super_contravariant = sub_contravariant; // Error +sub_contravariant = super_contravariant; + +type Invariant = { + f: (x: T) => T; +} + +declare let super_invariant: Invariant; +declare let sub_invariant: Invariant; + +super_invariant = sub_invariant; // Error +sub_invariant = super_invariant; // Error + +// Variance of various type constructors + +type T10 = T; +type T11 = keyof T; +type T12 = T[K]; +type T13 = T[keyof T]; + +// Variance annotation errors + +type Covariant1 = { // Error + x: T; +} + +type Contravariant1 = keyof T; // Error + +type Contravariant2 = { // Error + f: (x: T) => void; +} + +type Invariant1 = { // Error + f: (x: T) => T; +} + +type Invariant2 = { // Error + f: (x: T) => T; +} + +// Variance in circular types + +type Foo1 = { // Error + x: T; + f: FooFn1; +} + +type FooFn1 = (foo: Bar1) => void; + +type Bar1 = { + value: Foo1; +} + +type Foo2 = { // Error + x: T; + f: FooFn2; +} + +type FooFn2 = (foo: Bar2) => void; + +type Bar2 = { + value: Foo2; +} + +type Foo3 = { + x: T; + f: FooFn3; +} + +type FooFn3 = (foo: Bar3) => void; + +type Bar3 = { + value: Foo3; +} + +// Wrong modifier usage + +type T20 = T; // Error +type T21 = T; // Error +type T22 = T; // Error +type T23 = T; // Error + +declare function f1(x: T): void; // Error +declare function f2(): T; // Error + +class C { + in a = 0; // Error + out b = 0; // Error +} + +// Interface merging + +interface Baz {} +interface Baz {} + +declare let baz1: Baz; +declare let baz2: Baz; + +baz1 = baz2; // Error +baz2 = baz1; // Error + +// Repro from #44572 + +interface Parent { + child: Child | null; + parent: Parent | null; +} + +interface Child extends Parent { + readonly a: A; + readonly b: B; +} + +function fn(inp: Child) { + const a: Child = inp; +} + +const pu: Parent = { child: { a: 0, b: 0, child: null, parent: null }, parent: null }; +const notString: Parent = pu; // Error + +// Repro from comment in #44572 + +declare class StateNode { + _storedEvent: TEvent; + _action: ActionObject; + _state: StateNode; +} + +interface ActionObject { + exec: (meta: StateNode) => void; +} + +declare function createMachine(action: ActionObject): StateNode; + +declare function interpret(machine: StateNode): void; + +const machine = createMachine({} as any); + +interpret(machine); + +declare const qq: ActionObject<{ type: "PLAY"; value: number }>; + +createMachine<{ type: "PLAY"; value: number } | { type: "RESET" }>(qq); // Error diff --git a/tests/cases/conformance/types/uniqueSymbol/uniqueSymbolsDeclarationsInJs.ts b/tests/cases/conformance/types/uniqueSymbol/uniqueSymbolsDeclarationsInJs.ts index b01d4cc622e..77570833143 100644 --- a/tests/cases/conformance/types/uniqueSymbol/uniqueSymbolsDeclarationsInJs.ts +++ b/tests/cases/conformance/types/uniqueSymbol/uniqueSymbolsDeclarationsInJs.ts @@ -31,3 +31,6 @@ class C { readonlyCall = Symbol(); readwriteCall = Symbol(); } + +/** @type {unique symbol} */ +const a = Symbol(); diff --git a/tests/cases/fourslash/asConstRefsNoErrors1.ts b/tests/cases/fourslash/asConstRefsNoErrors1.ts new file mode 100644 index 00000000000..6bb63914c8c --- /dev/null +++ b/tests/cases/fourslash/asConstRefsNoErrors1.ts @@ -0,0 +1,8 @@ +/// + +////class Tex { +//// type = 'Text' as /**/const; +////} + +verify.goToDefinition("", []); +verify.noErrors(); \ No newline at end of file diff --git a/tests/cases/fourslash/asConstRefsNoErrors2.ts b/tests/cases/fourslash/asConstRefsNoErrors2.ts new file mode 100644 index 00000000000..74ea6a4e892 --- /dev/null +++ b/tests/cases/fourslash/asConstRefsNoErrors2.ts @@ -0,0 +1,8 @@ +/// + +////class Tex { +//// type = 'Text'; +////} + +verify.goToDefinition("", []); +verify.noErrors(); \ No newline at end of file diff --git a/tests/cases/fourslash/asConstRefsNoErrors3.ts b/tests/cases/fourslash/asConstRefsNoErrors3.ts new file mode 100644 index 00000000000..be450befafd --- /dev/null +++ b/tests/cases/fourslash/asConstRefsNoErrors3.ts @@ -0,0 +1,10 @@ +/// + +// @checkJs: true +// @Filename: file.js +////class Tex { +//// type = (/** @type {/**/const} */'Text'); +////} + +verify.goToDefinition("", []); +verify.noErrors(); \ No newline at end of file diff --git a/tests/cases/fourslash/codeFixAddMissingProperties_PreserveIndent.ts b/tests/cases/fourslash/codeFixAddMissingProperties_PreserveIndent.ts new file mode 100644 index 00000000000..01ab7a6b130 --- /dev/null +++ b/tests/cases/fourslash/codeFixAddMissingProperties_PreserveIndent.ts @@ -0,0 +1,50 @@ +/// + +////interface Test { +//// foo: string; +//// bar(a: string): void; +////} +////function f (_spec: any) {} +////function g (_spec: Test) {} +////[|f(() => { +//// g({}); +//// g( +//// {}); +//// g( +//// {} +//// ); +////});|] + +verify.codeFixAll({ + fixId: "fixMissingProperties", + fixAllDescription: ts.Diagnostics.Add_all_missing_properties.message, + newFileContent: `interface Test { + foo: string; + bar(a: string): void; +} +function f (_spec: any) {} +function g (_spec: Test) {} +f(() => { + g({ + foo: "", + bar: function(a: string): void { + throw new Error("Function not implemented."); + } + }); + g( + { + foo: "", + bar: function(a: string): void { + throw new Error("Function not implemented."); + } + }); + g( + { + foo: "", + bar: function(a: string): void { + throw new Error("Function not implemented."); + } + } + ); +});`, +}); diff --git a/tests/cases/fourslash/codeFixClassPropertyInitialization17.ts b/tests/cases/fourslash/codeFixClassPropertyInitialization17.ts new file mode 100644 index 00000000000..4e89c278553 --- /dev/null +++ b/tests/cases/fourslash/codeFixClassPropertyInitialization17.ts @@ -0,0 +1,17 @@ +/// + +// @strict: true + +//// class T { +//// // comment +//// a: string; +//// } + +verify.codeFix({ + description: `Add definite assignment assertion to property 'a: string;'`, + newFileContent: `class T { + // comment + a!: string; +}`, + index: 1 +}) diff --git a/tests/cases/fourslash/codeFixClassPropertyInitialization18.ts b/tests/cases/fourslash/codeFixClassPropertyInitialization18.ts new file mode 100644 index 00000000000..76dcbdb4e27 --- /dev/null +++ b/tests/cases/fourslash/codeFixClassPropertyInitialization18.ts @@ -0,0 +1,15 @@ +/// + +// @strict: true + +//// class T { +//// a: string; // comment +//// } + +verify.codeFix({ + description: `Add definite assignment assertion to property 'a: string;'`, + newFileContent: `class T { + a!: string; // comment +}`, + index: 1 +}) diff --git a/tests/cases/fourslash/codeFixClassPropertyInitialization19.ts b/tests/cases/fourslash/codeFixClassPropertyInitialization19.ts new file mode 100644 index 00000000000..727dd09aad1 --- /dev/null +++ b/tests/cases/fourslash/codeFixClassPropertyInitialization19.ts @@ -0,0 +1,17 @@ +/// + +// @strict: true + +//// class T { +//// // comment +//// a: 2; +//// } + +verify.codeFix({ + description: `Add initializer to property 'a'`, + newFileContent: `class T { + // comment + a: 2 = 2; +}`, + index: 2 +}) diff --git a/tests/cases/fourslash/codeFixClassPropertyInitialization20.ts b/tests/cases/fourslash/codeFixClassPropertyInitialization20.ts new file mode 100644 index 00000000000..35ccec948bc --- /dev/null +++ b/tests/cases/fourslash/codeFixClassPropertyInitialization20.ts @@ -0,0 +1,15 @@ +/// + +// @strict: true + +//// class T { +//// a: 2; // comment +//// } + +verify.codeFix({ + description: `Add initializer to property 'a'`, + newFileContent: `class T { + a: 2 = 2; // comment +}`, + index: 2 +}) diff --git a/tests/cases/fourslash/codefixUnreferenceableDecoratorMetadata1.ts b/tests/cases/fourslash/codefixUnreferenceableDecoratorMetadata1.ts new file mode 100644 index 00000000000..40f9a7239a7 --- /dev/null +++ b/tests/cases/fourslash/codefixUnreferenceableDecoratorMetadata1.ts @@ -0,0 +1,46 @@ +/// + +// @isolatedModules: true +// @module: es2015 +// @experimentalDecorators: true +// @emitDecoratorMetadata: true + +// @Filename: /mod.ts +//// export default interface I1 {} +//// export interface I2 {} + +// @Filename: /index.ts +//// [|import { I2 } from "./mod";|] +//// +//// declare var EventListener: any; +//// class HelloWorld { +//// @EventListener("1") +//// p1!: I2; +//// p2!: I2; +//// } + +const diag = ts.Diagnostics.A_type_referenced_in_a_decorated_signature_must_be_imported_with_import_type_or_a_namespace_import_when_isolatedModules_and_emitDecoratorMetadata_are_enabled; + +goTo.file("/index.ts"); + +verify.codeFix({ + index: 0, + description: ts.Diagnostics.Convert_named_imports_to_namespace_import.message, + errorCode: diag.code, + applyChanges: false, + newFileContent: `import * as mod from "./mod"; + +declare var EventListener: any; +class HelloWorld { + @EventListener("1") + p1!: mod.I2; + p2!: mod.I2; +}`, +}); + +verify.codeFix({ + index: 1, + description: ts.Diagnostics.Convert_to_type_only_import.message, + errorCode: diag.code, + newRangeContent: `import type { I2 } from "./mod";`, +}); diff --git a/tests/cases/fourslash/codefixUnreferenceableDecoratorMetadata2.ts b/tests/cases/fourslash/codefixUnreferenceableDecoratorMetadata2.ts new file mode 100644 index 00000000000..1ab14d1fc6a --- /dev/null +++ b/tests/cases/fourslash/codefixUnreferenceableDecoratorMetadata2.ts @@ -0,0 +1,38 @@ +/// + +// @isolatedModules: true +// @module: es2015 +// @experimentalDecorators: true +// @emitDecoratorMetadata: true + +// @Filename: /mod.ts +//// export default interface I1 {} +//// export interface I2 {} + +// @Filename: /index.ts +//// [|import I1, { I2 } from "./mod";|] +//// +//// declare var EventListener: any; +//// class HelloWorld { +//// @EventListener("1") +//// p1!: I2; +//// p2!: I2; +//// } + +const diag = ts.Diagnostics.A_type_referenced_in_a_decorated_signature_must_be_imported_with_import_type_or_a_namespace_import_when_isolatedModules_and_emitDecoratorMetadata_are_enabled; + +goTo.file("/index.ts"); + +verify.codeFix({ + description: ts.Diagnostics.Convert_named_imports_to_namespace_import.message, + errorCode: diag.code, + applyChanges: false, + newFileContent: `import I1, * as mod from "./mod"; + +declare var EventListener: any; +class HelloWorld { + @EventListener("1") + p1!: mod.I2; + p2!: mod.I2; +}`, +}); diff --git a/tests/cases/fourslash/codefixUnreferenceableDecoratorMetadata3.ts b/tests/cases/fourslash/codefixUnreferenceableDecoratorMetadata3.ts new file mode 100644 index 00000000000..7a7c66917c8 --- /dev/null +++ b/tests/cases/fourslash/codefixUnreferenceableDecoratorMetadata3.ts @@ -0,0 +1,55 @@ +/// + +// @isolatedModules: true +// @module: es2015 +// @experimentalDecorators: true +// @emitDecoratorMetadata: true + +// @Filename: /mod.ts +//// export default interface I1 {} +//// export interface I2 {} +//// export class C1 {} + +// @Filename: /index.ts +//// import I1, { I2 } from "./mod"; +//// +//// declare var EventListener: any; +//// export class HelloWorld { +//// @EventListener("1") +//// p1!: I1; +//// p2!: I2; +//// } + +// @Filename: /index2.ts +//// import { C1, I2 } from "./mod"; +//// +//// declare var EventListener: any; +//// export class HelloWorld { +//// @EventListener("1") +//// p1!: I2; +//// p2!: C1; +//// } + +const diag = ts.Diagnostics.A_type_referenced_in_a_decorated_signature_must_be_imported_with_import_type_or_a_namespace_import_when_isolatedModules_and_emitDecoratorMetadata_are_enabled; + +goTo.file("/index.ts"); +verify.not.codeFixAvailable(); + +// Mostly verifying that the type-only fix is not available +// (if both were available you'd have to specify `index` +// in `verify.codeFix`). +goTo.file("/index2.ts"); +verify.codeFix({ + description: ts.Diagnostics.Convert_named_imports_to_namespace_import.message, + errorCode: diag.code, + applyChanges: false, + newFileContent: `import * as mod from "./mod"; + +declare var EventListener: any; +export class HelloWorld { + @EventListener("1") + p1!: mod.I2; + p2!: mod.C1; +}`, +}); + diff --git a/tests/cases/fourslash/completionListInObjectLiteral7.ts b/tests/cases/fourslash/completionListInObjectLiteral7.ts new file mode 100644 index 00000000000..6f933ffb470 --- /dev/null +++ b/tests/cases/fourslash/completionListInObjectLiteral7.ts @@ -0,0 +1,17 @@ +/// + +////type Foo = { foo: boolean }; +////function f(shape: Foo): any; +////function f(shape: () => Foo): any; +////function f(arg: any) { +//// return arg; +////} +//// +////f({ /*1*/ }); +////f(() => ({ /*2*/ })); +////f(() => (({ /*3*/ }))); + +verify.completions({ + marker: ["1", "2", "3"], + exact: ["foo"] +}); diff --git a/tests/cases/fourslash/completionsOverridingMethod.ts b/tests/cases/fourslash/completionsOverridingMethod.ts index dc2623ea18b..d88abd77124 100644 --- a/tests/cases/fourslash/completionsOverridingMethod.ts +++ b/tests/cases/fourslash/completionsOverridingMethod.ts @@ -123,7 +123,7 @@ verify.completions({ includes: [ { name: "foo", - sortText: completion.SortText.LocationPriority, + sortText: completion.SortText.ClassMemberSnippets, insertText: "foo(param1: string, param2: boolean): Promise {\n}", } ], @@ -140,7 +140,7 @@ verify.completions({ includes: [ { name: "foo", - sortText: completion.SortText.LocationPriority, + sortText: completion.SortText.ClassMemberSnippets, insertText: "foo(a: string, b: string): string {\n}", } ], @@ -157,7 +157,7 @@ verify.completions({ includes: [ { name: "foo", - sortText: completion.SortText.LocationPriority, + sortText: completion.SortText.ClassMemberSnippets, insertText: "foo(a: string): string {\n}", } ], @@ -174,7 +174,7 @@ verify.completions({ includes: [ { name: "foo", - sortText: completion.SortText.LocationPriority, + sortText: completion.SortText.ClassMemberSnippets, insertText: "foo(a: string): string {\n}", } ], @@ -191,7 +191,7 @@ verify.completions({ includes: [ { name: "foo", - sortText: completion.SortText.LocationPriority, + sortText: completion.SortText.ClassMemberSnippets, insertText: "foo(a: string): string {\n}", } ], @@ -208,7 +208,7 @@ verify.completions({ includes: [ { name: "foo", - sortText: completion.SortText.LocationPriority, + sortText: completion.SortText.ClassMemberSnippets, insertText: "foo(a: string): string {\n}", } ], @@ -225,7 +225,7 @@ verify.completions({ includes: [ { name: "foo", - sortText: completion.SortText.LocationPriority, + sortText: completion.SortText.ClassMemberSnippets, insertText: `foo(a: string): string; foo(a: undefined, b: number): string; @@ -256,7 +256,7 @@ verify.completions({ includes: [ { name: "met", - sortText: completion.SortText.LocationPriority, + sortText: completion.SortText.ClassMemberSnippets, replacementSpan: test.ranges()[0], insertText: "static met(n: number): number {\n}", } @@ -274,12 +274,12 @@ verify.completions({ includes: [ { name: "met", - sortText: completion.SortText.LocationPriority, + sortText: completion.SortText.ClassMemberSnippets, insertText: "met(t: T): T {\n}", }, { name: "metcons", - sortText: completion.SortText.LocationPriority, + sortText: completion.SortText.ClassMemberSnippets, insertText: "metcons(t: T): T {\n}", } ], diff --git a/tests/cases/fourslash/completionsOverridingMethod1.ts b/tests/cases/fourslash/completionsOverridingMethod1.ts index 8158e0cda52..5e9349bc479 100644 --- a/tests/cases/fourslash/completionsOverridingMethod1.ts +++ b/tests/cases/fourslash/completionsOverridingMethod1.ts @@ -24,7 +24,7 @@ verify.completions({ includes: [ { name: "foo", - sortText: completion.SortText.LocationPriority, + sortText: completion.SortText.ClassMemberSnippets, insertText: "override foo(a: string): void {\n}", } ], diff --git a/tests/cases/fourslash/completionsOverridingMethod10.ts b/tests/cases/fourslash/completionsOverridingMethod10.ts index 44180fe547e..af8681ad37d 100644 --- a/tests/cases/fourslash/completionsOverridingMethod10.ts +++ b/tests/cases/fourslash/completionsOverridingMethod10.ts @@ -25,19 +25,19 @@ verify.completions({ includes: [ { name: "a", - sortText: completion.SortText.LocationPriority, + sortText: completion.SortText.ClassMemberSnippets, insertText: "a: string;", }, { name: "b", - sortText: completion.SortText.LocationPriority, + sortText: completion.SortText.ClassMemberSnippets, insertText: `b(a: string): void { }`, }, { name: "c", - sortText: completion.SortText.LocationPriority, + sortText: completion.SortText.ClassMemberSnippets, insertText: `c(a: string): string; c(a: number): number; diff --git a/tests/cases/fourslash/completionsOverridingMethod11.ts b/tests/cases/fourslash/completionsOverridingMethod11.ts index e613bbdf078..4cf3c4f606c 100644 --- a/tests/cases/fourslash/completionsOverridingMethod11.ts +++ b/tests/cases/fourslash/completionsOverridingMethod11.ts @@ -31,19 +31,19 @@ verify.completions({ includes: [ { name: "a", - sortText: completion.SortText.LocationPriority, + sortText: completion.SortText.ClassMemberSnippets, insertText: "a: string", }, { name: "b", - sortText: completion.SortText.LocationPriority, + sortText: completion.SortText.ClassMemberSnippets, insertText: `b(a: string): void { }`, }, { name: "c", - sortText: completion.SortText.LocationPriority, + sortText: completion.SortText.ClassMemberSnippets, insertText: `c(a: string): string c(a: number): number diff --git a/tests/cases/fourslash/completionsOverridingMethod12.ts b/tests/cases/fourslash/completionsOverridingMethod12.ts index 6a13f2ae577..c929ad1ca40 100644 --- a/tests/cases/fourslash/completionsOverridingMethod12.ts +++ b/tests/cases/fourslash/completionsOverridingMethod12.ts @@ -28,7 +28,7 @@ verify.completions({ includes: [ { name: "P", - sortText: completion.SortText.LocationPriority, + sortText: completion.SortText.ClassMemberSnippets, replacementSpan: test.ranges()[0], insertText: "public abstract get P(): string;", }, @@ -46,7 +46,7 @@ verify.completions({ includes: [ { name: "P", - sortText: completion.SortText.LocationPriority, + sortText: completion.SortText.ClassMemberSnippets, replacementSpan: test.ranges()[1], insertText: "public abstract override get P(): string;", }, diff --git a/tests/cases/fourslash/completionsOverridingMethod13.ts b/tests/cases/fourslash/completionsOverridingMethod13.ts new file mode 100644 index 00000000000..e8422a8bbc7 --- /dev/null +++ b/tests/cases/fourslash/completionsOverridingMethod13.ts @@ -0,0 +1,31 @@ +/// + +// @Filename: a.ts +// @newline: LF + +////class A { +//// protected foo(): void { +//// return; +//// } +////} +////class B extends A { +//// /**/ +////} + +verify.completions({ + marker: "", + isNewIdentifierLocation: true, + preferences: { + includeCompletionsWithInsertText: true, + includeCompletionsWithSnippetText: false, + includeCompletionsWithClassMemberSnippets: true, + }, + exact: [ + ...completion.classElementKeywords, + { + name: "foo", + sortText: completion.SortText.ClassMemberSnippets, + insertText: "protected foo(): void {\n}", + }, + ], +}); diff --git a/tests/cases/fourslash/completionsOverridingMethod2.ts b/tests/cases/fourslash/completionsOverridingMethod2.ts index 5a134e8aeab..4abdbfa2707 100644 --- a/tests/cases/fourslash/completionsOverridingMethod2.ts +++ b/tests/cases/fourslash/completionsOverridingMethod2.ts @@ -22,7 +22,7 @@ verify.completions({ includes: [ { name: "$usd", - sortText: completion.SortText.LocationPriority, + sortText: completion.SortText.ClassMemberSnippets, isSnippet: true, insertText: "\"\\$usd\"(a: number): number {\n $0\n}", } diff --git a/tests/cases/fourslash/completionsOverridingMethod3.ts b/tests/cases/fourslash/completionsOverridingMethod3.ts index ac4081cdd26..e3baffe1466 100644 --- a/tests/cases/fourslash/completionsOverridingMethod3.ts +++ b/tests/cases/fourslash/completionsOverridingMethod3.ts @@ -23,7 +23,7 @@ verify.completions({ includes: [ { name: "boo", - sortText: completion.SortText.LocationPriority, + sortText: completion.SortText.ClassMemberSnippets, insertText: "boo(): string;", } ], diff --git a/tests/cases/fourslash/completionsOverridingMethod4.ts b/tests/cases/fourslash/completionsOverridingMethod4.ts index 5c0f0f1ae06..3d5fbb045e3 100644 --- a/tests/cases/fourslash/completionsOverridingMethod4.ts +++ b/tests/cases/fourslash/completionsOverridingMethod4.ts @@ -42,12 +42,12 @@ verify.completions({ includes: [ { name: "hint", - sortText: completion.SortText.LocationPriority, + sortText: completion.SortText.ClassMemberSnippets, insertText: "protected hint(): string {\n}", }, { name: "refuse", - sortText: completion.SortText.LocationPriority, + sortText: completion.SortText.ClassMemberSnippets, insertText: "public refuse(): string {\n}", } ], diff --git a/tests/cases/fourslash/completionsOverridingMethod5.ts b/tests/cases/fourslash/completionsOverridingMethod5.ts index d2638434146..3f3844567a7 100644 --- a/tests/cases/fourslash/completionsOverridingMethod5.ts +++ b/tests/cases/fourslash/completionsOverridingMethod5.ts @@ -28,12 +28,12 @@ verify.completions({ includes: [ { name: "met", - sortText: completion.SortText.LocationPriority, + sortText: completion.SortText.ClassMemberSnippets, insertText: "met(n: string): void {\n}", }, { name: "met2", - sortText: completion.SortText.LocationPriority, + sortText: completion.SortText.ClassMemberSnippets, insertText: "met2(n: number): void {\n}", } ], @@ -50,13 +50,13 @@ verify.completions({ includes: [ { name: "met", - sortText: completion.SortText.LocationPriority, + sortText: completion.SortText.ClassMemberSnippets, replacementSpan: test.ranges()[0], insertText: "abstract met(n: string): void;", }, { name: "met2", - sortText: completion.SortText.LocationPriority, + sortText: completion.SortText.ClassMemberSnippets, replacementSpan: test.ranges()[0], insertText: "abstract met2(n: number): void;", } @@ -74,13 +74,13 @@ verify.completions({ includes: [ { name: "met", - sortText: completion.SortText.LocationPriority, + sortText: completion.SortText.ClassMemberSnippets, replacementSpan: test.ranges()[1], insertText: "abstract met(n: string): void;", }, { name: "met2", - sortText: completion.SortText.LocationPriority, + sortText: completion.SortText.ClassMemberSnippets, replacementSpan: test.ranges()[1], insertText: "abstract met2(n: number): void;", } diff --git a/tests/cases/fourslash/completionsOverridingMethod6.ts b/tests/cases/fourslash/completionsOverridingMethod6.ts index 4b97adba9bb..6e1dd428a30 100644 --- a/tests/cases/fourslash/completionsOverridingMethod6.ts +++ b/tests/cases/fourslash/completionsOverridingMethod6.ts @@ -37,7 +37,7 @@ verify.completions({ includes: [ { name: "method", - sortText: completion.SortText.LocationPriority, + sortText: completion.SortText.ClassMemberSnippets, replacementSpan: test.ranges()[1], insertText: "public override method(): number {\n}", }, @@ -55,7 +55,7 @@ verify.completions({ includes: [ { name: "method", - sortText: completion.SortText.LocationPriority, + sortText: completion.SortText.ClassMemberSnippets, replacementSpan: test.ranges()[0], insertText: "public abstract method(): number;", }, @@ -73,7 +73,7 @@ verify.completions({ includes: [ { name: "fun", - sortText: completion.SortText.LocationPriority, + sortText: completion.SortText.ClassMemberSnippets, replacementSpan: test.ranges()[2], insertText: `public fun(a: number): number; diff --git a/tests/cases/fourslash/completionsOverridingMethod7.ts b/tests/cases/fourslash/completionsOverridingMethod7.ts index 051c518a0ad..67865a5ef34 100644 --- a/tests/cases/fourslash/completionsOverridingMethod7.ts +++ b/tests/cases/fourslash/completionsOverridingMethod7.ts @@ -23,7 +23,7 @@ verify.completions({ includes: [ { name: "M", - sortText: completion.SortText.LocationPriority, + sortText: completion.SortText.ClassMemberSnippets, replacementSpan: test.ranges()[0], insertText: `abstract M(t: T): void; diff --git a/tests/cases/fourslash/completionsOverridingMethod8.ts b/tests/cases/fourslash/completionsOverridingMethod8.ts index cd717aae5d4..3e5aea9dd97 100644 --- a/tests/cases/fourslash/completionsOverridingMethod8.ts +++ b/tests/cases/fourslash/completionsOverridingMethod8.ts @@ -26,7 +26,7 @@ verify.completions({ }, includes: [{ name: "method", - sortText: completion.SortText.LocationPriority, + sortText: completion.SortText.ClassMemberSnippets, insertText: "method(p: I): void {\n}", hasAction: true, source: completion.CompletionSource.ClassMemberSnippet, diff --git a/tests/cases/fourslash/completionsOverridingMethod9.ts b/tests/cases/fourslash/completionsOverridingMethod9.ts index 5ce63927083..204ecbbcc49 100644 --- a/tests/cases/fourslash/completionsOverridingMethod9.ts +++ b/tests/cases/fourslash/completionsOverridingMethod9.ts @@ -22,12 +22,12 @@ verify.completions({ includes: [ { name: "a", - sortText: completion.SortText.LocationPriority, + sortText: completion.SortText.ClassMemberSnippets, insertText: "a?: number;" }, { name: "b", - sortText: completion.SortText.LocationPriority, + sortText: completion.SortText.ClassMemberSnippets, insertText: "b(x: number): void {\n}" }, ], diff --git a/tests/cases/fourslash/completionsOverridingProperties.ts b/tests/cases/fourslash/completionsOverridingProperties.ts index fad97f78fd6..f25fee59150 100644 --- a/tests/cases/fourslash/completionsOverridingProperties.ts +++ b/tests/cases/fourslash/completionsOverridingProperties.ts @@ -25,12 +25,7 @@ verify.completions({ includes: [ { name: "foo", - sortText: completion.SortText.LocationPriority, - replacementSpan: { - fileName: "", - pos: 0, - end: 0, - }, + sortText: completion.SortText.ClassMemberSnippets, insertText: "protected foo: string;", } ], diff --git a/tests/cases/fourslash/convertFunctionToEs6Class1.ts b/tests/cases/fourslash/convertFunctionToEs6Class1.ts index a0046fc4e90..c99a2efe7d0 100644 --- a/tests/cases/fourslash/convertFunctionToEs6Class1.ts +++ b/tests/cases/fourslash/convertFunctionToEs6Class1.ts @@ -21,10 +21,10 @@ verify.codeFix({ newFileContent: `class foo { constructor() { } - instanceMethod1() { return "this is name"; } - instanceMethod2() { return "this is name"; } static staticMethod1() { return "this is static name"; } static staticMethod2() { return "this is static name"; } + instanceMethod1() { return "this is name"; } + instanceMethod2() { return "this is name"; } } foo.prototype.instanceProp1 = "hello"; foo.prototype.instanceProp2 = undefined; diff --git a/tests/cases/fourslash/convertFunctionToEs6Class2.ts b/tests/cases/fourslash/convertFunctionToEs6Class2.ts index 5326c30eea4..f8395a8484d 100644 --- a/tests/cases/fourslash/convertFunctionToEs6Class2.ts +++ b/tests/cases/fourslash/convertFunctionToEs6Class2.ts @@ -16,10 +16,10 @@ verify.codeFix({ newFileContent: `class foo { constructor() { } - instanceMethod1() { return "this is name"; } - instanceMethod2() { return "this is name"; } static staticMethod1() { return "this is static name"; } static staticMethod2() { return "this is static name"; } + instanceMethod1() { return "this is name"; } + instanceMethod2() { return "this is name"; } } foo.instanceProp1 = "hello"; foo.instanceProp2 = undefined; diff --git a/tests/cases/fourslash/convertFunctionToEs6Class3.ts b/tests/cases/fourslash/convertFunctionToEs6Class3.ts index d88c4b80a8d..8b4bbd7f22b 100644 --- a/tests/cases/fourslash/convertFunctionToEs6Class3.ts +++ b/tests/cases/fourslash/convertFunctionToEs6Class3.ts @@ -17,10 +17,10 @@ verify.codeFix({ `var bar = 10; class foo { constructor() { } - instanceMethod1() { return "this is name"; } - instanceMethod2() { return "this is name"; } static staticMethod1() { return "this is static name"; } static staticMethod2() { return "this is static name"; } + instanceMethod1() { return "this is name"; } + instanceMethod2() { return "this is name"; } } foo.prototype.instanceProp1 = "hello"; foo.prototype.instanceProp2 = undefined; diff --git a/tests/cases/fourslash/convertFunctionToEs6Class_asyncMethods.ts b/tests/cases/fourslash/convertFunctionToEs6Class_asyncMethods.ts index bb8f8c22962..ab5bcb61ab4 100644 --- a/tests/cases/fourslash/convertFunctionToEs6Class_asyncMethods.ts +++ b/tests/cases/fourslash/convertFunctionToEs6Class_asyncMethods.ts @@ -18,10 +18,10 @@ verify.codeFix({ `export class MyClass { constructor() { } - async foo() { + static async bar() { await Promise.resolve(); } - static async bar() { + async foo() { await Promise.resolve(); } } diff --git a/tests/cases/fourslash/formatOnTypeOpenCurlyWithBraceCompletion.ts b/tests/cases/fourslash/formatOnTypeOpenCurlyWithBraceCompletion.ts new file mode 100644 index 00000000000..b303b1ea62d --- /dev/null +++ b/tests/cases/fourslash/formatOnTypeOpenCurlyWithBraceCompletion.ts @@ -0,0 +1,12 @@ +/// + +//// if (foo) { +//// if (bar) {/**/} +//// } + +goTo.marker(""); +format.onType("", "{"); +verify.currentFileContentIs( +`if (foo) { + if (bar) { } +}`); diff --git a/tests/cases/fourslash/fourslash.ts b/tests/cases/fourslash/fourslash.ts index 955d87c6f63..1ed08b3a020 100644 --- a/tests/cases/fourslash/fourslash.ts +++ b/tests/cases/fourslash/fourslash.ts @@ -846,14 +846,15 @@ declare namespace completion { SuggestedClassMembers = "14", GlobalsOrKeywords = "15", AutoImportSuggestions = "16", - JavascriptIdentifiers = "17", - DeprecatedLocalDeclarationPriority = "18", - DeprecatedLocationPriority = "19", - DeprecatedOptionalMember = "20", - DeprecatedMemberDeclaredBySpreadAssignment = "21", - DeprecatedSuggestedClassMembers = "22", - DeprecatedGlobalsOrKeywords = "23", - DeprecatedAutoImportSuggestions = "24" + ClassMemberSnippets = "17", + JavascriptIdentifiers = "18", + DeprecatedLocalDeclarationPriority = "19", + DeprecatedLocationPriority = "20", + DeprecatedOptionalMember = "21", + DeprecatedMemberDeclaredBySpreadAssignment = "22", + DeprecatedSuggestedClassMembers = "23", + DeprecatedGlobalsOrKeywords = "24", + DeprecatedAutoImportSuggestions = "25" } export const enum CompletionSource { ThisProperty = "ThisProperty/", diff --git a/tests/cases/fourslash/importFixesGlobalTypingsCache.ts b/tests/cases/fourslash/importFixesGlobalTypingsCache.ts index 68eeae6f0fb..690af5820e3 100644 --- a/tests/cases/fourslash/importFixesGlobalTypingsCache.ts +++ b/tests/cases/fourslash/importFixesGlobalTypingsCache.ts @@ -4,11 +4,17 @@ //// { "compilerOptions": { "allowJs": true, "checkJs": true } } // @Filename: /Library/Caches/typescript/node_modules/@types/react-router-dom/package.json -//// { "name": "react-router-dom" } +//// { "name": "@types/react-router-dom", "version": "16.8.4", "types": "index.d.ts" } // @Filename: /Library/Caches/typescript/node_modules/@types/react-router-dom/index.d.ts ////export class BrowserRouter {} +// @Filename: /project/node_modules/react-router-dom/package.json +//// { "name": "react-router-dom", "version": "16.8.4", "main": "index.js" } + +// @Filename: /project/node_modules/react-router-dom/index.js +//// export const BrowserRouter = () => null; + // @Filename: /project/index.js ////BrowserRouter/**/ @@ -16,3 +22,4 @@ goTo.file("/project/index.js"); verify.importFixAtPosition([`const { BrowserRouter } = require("react-router-dom"); BrowserRouter`]); + diff --git a/tests/cases/fourslash/inlayHintsShouldWork66.ts b/tests/cases/fourslash/inlayHintsShouldWork66.ts new file mode 100644 index 00000000000..618348a6911 --- /dev/null +++ b/tests/cases/fourslash/inlayHintsShouldWork66.ts @@ -0,0 +1,23 @@ +/// + +////interface IFoo { +//// bar(x?: boolean): void; +////} +//// +////const a: IFoo = { +//// bar: function (x?/**/): void { +//// throw new Error("Function not implemented."); +//// } +////} + +const [marker] = test.markers(); +verify.getInlayHints([ + { + text: ': boolean', + position: marker.position, + kind: ts.InlayHintKind.Type, + whitespaceBefore: true + }, +], undefined, { + includeInlayFunctionParameterTypeHints: true +}); diff --git a/tests/cases/fourslash/server/autoImportProvider_globalTypingsCache.ts b/tests/cases/fourslash/server/autoImportProvider_globalTypingsCache.ts new file mode 100644 index 00000000000..7e7d22a71ba --- /dev/null +++ b/tests/cases/fourslash/server/autoImportProvider_globalTypingsCache.ts @@ -0,0 +1,41 @@ +/// + +// @Filename: /Library/Caches/typescript/node_modules/@types/react-router-dom/package.json +//// { "name": "@types/react-router-dom", "version": "16.8.4", "types": "index.d.ts" } + +// @Filename: /Library/Caches/typescript/node_modules/@types/react-router-dom/index.d.ts +//// export class BrowserRouterFromDts {} + +// @Filename: /project/package.json +//// { "dependencies": { "react-router-dom": "*" } } + +// @Filename: /project/tsconfig.json +//// { "compilerOptions": { "module": "commonjs", "allowJs": true, "checkJs": true, "maxNodeModuleJsDepth": 2 }, "typeAcquisition": { "enable": true } } + +// @Filename: /project/node_modules/react-router-dom/package.json +//// { "name": "react-router-dom", "version": "16.8.4", "main": "index.js" } + +// @Filename: /project/node_modules/react-router-dom/index.js +//// import "./BrowserRouter"; +//// export {}; + +// @Filename: /project/node_modules/react-router-dom/BrowserRouter.js +//// export const BrowserRouterFromJs = () => null; + +// @Filename: /project/index.js +////BrowserRouter/**/ + +verify.completions({ + marker: "", + exact: completion.globalsInJsPlus([{ + name: "BrowserRouterFromDts", + source: "react-router-dom", + sourceDisplay: "react-router-dom", + hasAction: true, + sortText: completion.SortText.AutoImportSuggestions, + }]), + preferences: { + allowIncompleteCompletions: true, + includeCompletionsForModuleExports: true, + } +}); diff --git a/tests/cases/fourslash/server/jsdocCallbackTag.ts b/tests/cases/fourslash/server/jsdocCallbackTag.ts index da58a38a957..df1b9e12969 100644 --- a/tests/cases/fourslash/server/jsdocCallbackTag.ts +++ b/tests/cases/fourslash/server/jsdocCallbackTag.ts @@ -30,6 +30,6 @@ verify.quickInfoIs("var t: FooHandler"); goTo.marker("2"); verify.quickInfoIs("var t2: FooHandler2"); goTo.marker("3"); -verify.quickInfoIs("type FooHandler2 = (eventName?: string | undefined, eventName2?: string) => any", "What, another one?"); +verify.quickInfoIs("type FooHandler2 = (eventName?: string | undefined, eventName2?: string) => any", "- What, another one?"); goTo.marker("8"); -verify.quickInfoIs("type FooHandler = (eventName: string, eventName2: number | string, eventName3: any) => number", "A kind of magic"); +verify.quickInfoIs("type FooHandler = (eventName: string, eventName2: number | string, eventName3: any) => number", "- A kind of magic"); diff --git a/tests/cases/fourslash/server/jsdocTypedefTag.ts b/tests/cases/fourslash/server/jsdocTypedefTag.ts index c2d73e981e0..ed27e6e29ef 100644 --- a/tests/cases/fourslash/server/jsdocTypedefTag.ts +++ b/tests/cases/fourslash/server/jsdocTypedefTag.ts @@ -71,4 +71,4 @@ verify.completions( { marker: "catAge", includes: "toExponential" }, ); -verify.quickInfoAt("AnimalType", "type Animal = {\n animalName: string;\n animalAge: number;\n}", "think Giraffes"); +verify.quickInfoAt("AnimalType", "type Animal = {\n animalName: string;\n animalAge: number;\n}", "- think Giraffes");