Merge branch 'master' into release-3.5

This commit is contained in:
Daniel Rosenwasser 2019-05-24 17:09:52 -07:00
commit 4e0fa10d55
313 changed files with 4351 additions and 1116 deletions

View File

@ -2515,7 +2515,7 @@ namespace ts {
break;
default:
Debug.fail(Debug.showSyntaxKind(thisContainer));
Debug.failBadSyntaxKind(thisContainer);
}
}
@ -2581,7 +2581,7 @@ namespace ts {
// Fix up parent pointers since we're going to use these nodes before we bind into them
node.left.parent = node;
node.right.parent = node;
if (isIdentifier(lhs.expression) && container === file && isNameOfExportsOrModuleExportsAliasDeclaration(file, lhs.expression)) {
if (isIdentifier(lhs.expression) && container === file && isExportsOrModuleExportsOrAlias(file, lhs.expression)) {
// This can be an alias for the 'exports' or 'module.exports' names, e.g.
// var util = module.exports;
// util.property = function ...
@ -2975,21 +2975,27 @@ namespace ts {
}
export function isExportsOrModuleExportsOrAlias(sourceFile: SourceFile, node: Expression): boolean {
return isExportsIdentifier(node) ||
isModuleExportsPropertyAccessExpression(node) ||
isIdentifier(node) && isNameOfExportsOrModuleExportsAliasDeclaration(sourceFile, node);
}
function isNameOfExportsOrModuleExportsAliasDeclaration(sourceFile: SourceFile, node: Identifier): boolean {
const symbol = lookupSymbolForNameWorker(sourceFile, node.escapedText);
return !!symbol && !!symbol.valueDeclaration && isVariableDeclaration(symbol.valueDeclaration) &&
!!symbol.valueDeclaration.initializer && isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, symbol.valueDeclaration.initializer);
}
function isExportsOrModuleExportsOrAliasOrAssignment(sourceFile: SourceFile, node: Expression): boolean {
return isExportsOrModuleExportsOrAlias(sourceFile, node) ||
(isAssignmentExpression(node, /*excludeCompoundAssignment*/ true) && (
isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, node.left) || isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, node.right)));
let i = 0;
const q = [node];
while (q.length && i < 100) {
i++;
node = q.shift()!;
if (isExportsIdentifier(node) || isModuleExportsPropertyAccessExpression(node)) {
return true;
}
else if (isIdentifier(node)) {
const symbol = lookupSymbolForNameWorker(sourceFile, node.escapedText);
if (!!symbol && !!symbol.valueDeclaration && isVariableDeclaration(symbol.valueDeclaration) && !!symbol.valueDeclaration.initializer) {
const init = symbol.valueDeclaration.initializer;
q.push(init);
if (isAssignmentExpression(init, /*excludeCompoundAssignment*/ true)) {
q.push(init.left);
q.push(init.right);
}
}
}
}
return false;
}
function lookupSymbolForNameWorker(container: Node, name: __String): Symbol | undefined {

View File

@ -182,6 +182,10 @@ namespace ts {
node = getParseTreeNode(node);
return node ? getTypeOfNode(node) : errorType;
},
getTypeOfAssignmentPattern: nodeIn => {
const node = getParseTreeNode(nodeIn, isAssignmentPattern);
return node && getTypeOfAssignmentPattern(node) || errorType;
},
getPropertySymbolOfDestructuringAssignment: locationIn => {
const location = getParseTreeNode(locationIn, isIdentifier);
return location ? getPropertySymbolOfDestructuringAssignment(location) : undefined;
@ -391,7 +395,7 @@ namespace ts {
const tupleTypes = createMap<GenericType>();
const unionTypes = createMap<UnionType>();
const intersectionTypes = createMap<IntersectionType>();
const intersectionTypes = createMap<Type>();
const literalTypes = createMap<LiteralType>();
const indexedAccessTypes = createMap<IndexedAccessType>();
const substitutionTypes = createMap<SubstitutionType>();
@ -3563,7 +3567,7 @@ namespace ts {
context.approximateLength += 6;
return createKeywordTypeNode(SyntaxKind.ObjectKeyword);
}
if (type.flags & TypeFlags.TypeParameter && (type as TypeParameter).isThisType) {
if (isThisTypeParameter(type)) {
if (context.flags & NodeBuilderFlags.InObjectTypeLiteral) {
if (!context.encounteredError && !(context.flags & NodeBuilderFlags.AllowThisInObjectLiteral)) {
context.encounteredError = true;
@ -4302,6 +4306,11 @@ namespace ts {
function lookupTypeParameterNodes(chain: Symbol[], index: number, context: NodeBuilderContext) {
Debug.assert(chain && 0 <= index && index < chain.length);
const symbol = chain[index];
const symbolId = "" + getSymbolId(symbol);
if (context.typeParameterSymbolList && context.typeParameterSymbolList.get(symbolId)) {
return undefined;
}
(context.typeParameterSymbolList || (context.typeParameterSymbolList = createMap())).set(symbolId, true);
let typeParameterNodes: ReadonlyArray<TypeNode> | ReadonlyArray<TypeParameterDeclaration> | undefined;
if (context.flags & NodeBuilderFlags.WriteTypeParametersInQualifiedName && index < (chain.length - 1)) {
const parentSymbol = symbol;
@ -4628,6 +4637,7 @@ namespace ts {
inferTypeParameters: TypeParameter[] | undefined;
approximateLength: number;
truncating?: boolean;
typeParameterSymbolList?: Map<true>;
}
function isDefaultBindingContext(location: Node) {
@ -5346,7 +5356,7 @@ namespace ts {
return type;
}
else if (declaredType !== errorType && type !== errorType && !isTypeIdenticalTo(declaredType, type)) {
errorNextVariableOrPropertyDeclarationMustHaveSameType(declaredType, declaration, type);
errorNextVariableOrPropertyDeclarationMustHaveSameType(/*firstDeclaration*/ undefined, declaredType, declaration, type);
}
}
return declaredType;
@ -5689,7 +5699,7 @@ namespace ts {
type = getTypeOfEnumMember(symbol);
}
else {
return Debug.fail("Unhandled declaration kind! " + Debug.showSyntaxKind(declaration) + " for " + Debug.showSymbol(symbol));
return Debug.fail("Unhandled declaration kind! " + Debug.formatSyntaxKind(declaration.kind) + " for " + Debug.formatSymbol(symbol));
}
if (!popTypeResolution()) {
@ -7046,10 +7056,10 @@ namespace ts {
// Union the result types when more than one signature matches
if (unionSignatures.length > 1) {
let thisParameter = signature.thisParameter;
if (forEach(unionSignatures, sig => sig.thisParameter)) {
// TODO: GH#18217 We tested that *some* has thisParameter and now act as if *all* do
const firstThisParameterOfUnionSignatures = forEach(unionSignatures, sig => sig.thisParameter);
if (firstThisParameterOfUnionSignatures) {
const thisType = getUnionType(map(unionSignatures, sig => sig.thisParameter ? getTypeOfSymbol(sig.thisParameter) : anyType), UnionReduction.Subtype);
thisParameter = createSymbolWithType(signature.thisParameter!, thisType);
thisParameter = createSymbolWithType(firstThisParameterOfUnionSignatures, thisType);
}
s = createUnionSignature(signature, unionSignatures);
s.thisParameter = thisParameter;
@ -7651,15 +7661,20 @@ namespace ts {
return hasNonCircularBaseConstraint(type) ? getConstraintFromIndexedAccess(type) : undefined;
}
function getSimplifiedTypeOrConstraint(type: Type) {
const simplified = getSimplifiedType(type, /*writing*/ false);
return simplified !== type ? simplified : getConstraintOfType(type);
}
function getConstraintFromIndexedAccess(type: IndexedAccessType) {
const indexConstraint = getConstraintOfType(type.indexType);
const indexConstraint = getSimplifiedTypeOrConstraint(type.indexType);
if (indexConstraint && indexConstraint !== type.indexType) {
const indexedAccess = getIndexedAccessTypeOrUndefined(type.objectType, indexConstraint);
if (indexedAccess) {
return indexedAccess;
}
}
const objectConstraint = getConstraintOfType(type.objectType);
const objectConstraint = getSimplifiedTypeOrConstraint(type.objectType);
if (objectConstraint && objectConstraint !== type.objectType) {
return getIndexedAccessTypeOrUndefined(objectConstraint, type.indexType);
}
@ -9838,6 +9853,15 @@ namespace ts {
return true;
}
function createIntersectionType(types: Type[], aliasSymbol?: Symbol, aliasTypeArguments?: ReadonlyArray<Type>) {
const result = <IntersectionType>createType(TypeFlags.Intersection);
result.objectFlags = getPropagatingFlagsOfTypes(types, /*excludeKinds*/ TypeFlags.Nullable);
result.types = types;
result.aliasSymbol = aliasSymbol; // See comment in `getUnionTypeFromSortedList`.
result.aliasTypeArguments = aliasTypeArguments;
return result;
}
// We normalize combinations of intersection and union types based on the distributive property of the '&'
// operator. Specifically, because X & (A | B) is equivalent to X & A | X & B, we can transform intersection
// types with union type constituents into equivalent union types with intersection type constituents and
@ -9875,31 +9899,37 @@ namespace ts {
if (typeSet.length === 1) {
return typeSet[0];
}
if (includes & TypeFlags.Union) {
if (intersectUnionsOfPrimitiveTypes(typeSet)) {
// When the intersection creates a reduced set (which might mean that *all* union types have
// disappeared), we restart the operation to get a new set of combined flags. Once we have
// reduced we'll never reduce again, so this occurs at most once.
return getIntersectionType(typeSet, aliasSymbol, aliasTypeArguments);
}
// We are attempting to construct a type of the form X & (A | B) & Y. Transform this into a type of
// the form X & A & Y | X & B & Y and recursively reduce until no union type constituents remain.
const unionIndex = findIndex(typeSet, t => (t.flags & TypeFlags.Union) !== 0);
const unionType = <UnionType>typeSet[unionIndex];
return getUnionType(map(unionType.types, t => getIntersectionType(replaceElement(typeSet, unionIndex, t))),
UnionReduction.Literal, aliasSymbol, aliasTypeArguments);
}
const id = getTypeListId(typeSet);
let type = intersectionTypes.get(id);
if (!type) {
type = <IntersectionType>createType(TypeFlags.Intersection);
intersectionTypes.set(id, type);
type.objectFlags = getPropagatingFlagsOfTypes(typeSet, /*excludeKinds*/ TypeFlags.Nullable);
type.types = typeSet;
type.aliasSymbol = aliasSymbol; // See comment in `getUnionTypeFromSortedList`.
type.aliasTypeArguments = aliasTypeArguments;
let result = intersectionTypes.get(id);
if (!result) {
if (includes & TypeFlags.Union) {
if (intersectUnionsOfPrimitiveTypes(typeSet)) {
// When the intersection creates a reduced set (which might mean that *all* union types have
// disappeared), we restart the operation to get a new set of combined flags. Once we have
// reduced we'll never reduce again, so this occurs at most once.
result = getIntersectionType(typeSet, aliasSymbol, aliasTypeArguments);
}
else {
// We are attempting to construct a type of the form X & (A | B) & Y. Transform this into a type of
// the form X & A & Y | X & B & Y and recursively reduce until no union type constituents remain.
// If the estimated size of the resulting union type exceeds 100000 constituents, report an error.
const size = reduceLeft(typeSet, (n, t) => n * (t.flags & TypeFlags.Union ? (<UnionType>t).types.length : 1), 1);
if (size >= 100000) {
error(currentNode, Diagnostics.Expression_produces_a_union_type_that_is_too_complex_to_represent);
return errorType;
}
const unionIndex = findIndex(typeSet, t => (t.flags & TypeFlags.Union) !== 0);
const unionType = <UnionType>typeSet[unionIndex];
result = getUnionType(map(unionType.types, t => getIntersectionType(replaceElement(typeSet, unionIndex, t))),
UnionReduction.Literal, aliasSymbol, aliasTypeArguments);
}
}
else {
result = createIntersectionType(typeSet, aliasSymbol, aliasTypeArguments);
}
intersectionTypes.set(id, result);
}
return type;
return result;
}
function getTypeFromIntersectionTypeNode(node: IntersectionTypeNode): Type {
@ -10047,7 +10077,7 @@ namespace ts {
return false;
}
function getPropertyTypeForIndexType(originalObjectType: Type, objectType: Type, indexType: Type, accessNode: ElementAccessExpression | IndexedAccessTypeNode | PropertyName | BindingName | SyntheticExpression | undefined, accessFlags: AccessFlags) {
function getPropertyTypeForIndexType(originalObjectType: Type, objectType: Type, indexType: Type, fullIndexType: Type, suppressNoImplicitAnyError: boolean, accessNode: ElementAccessExpression | IndexedAccessTypeNode | PropertyName | BindingName | SyntheticExpression | undefined, accessFlags: AccessFlags) {
const accessExpression = accessNode && accessNode.kind === SyntaxKind.ElementAccessExpression ? accessNode : undefined;
const propName = isTypeUsableAsPropertyName(indexType) ?
getPropertyNameFromType(indexType) :
@ -10086,6 +10116,7 @@ namespace ts {
error(indexNode, Diagnostics.Property_0_does_not_exist_on_type_1, unescapeLeadingUnderscores(propName), typeToString(objectType));
}
}
errorIfWritingToReadonlyIndex(getIndexInfoOfType(objectType, IndexKind.Number));
return mapType(objectType, t => getRestTypeOfTupleType(<TupleTypeReference>t) || undefinedType);
}
}
@ -10107,13 +10138,7 @@ namespace ts {
error(indexNode, Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType));
return indexInfo.type;
}
if (indexInfo.isReadonly && accessExpression && (isAssignmentTarget(accessExpression) || isDeleteTarget(accessExpression))) {
if (accessExpression) {
error(accessExpression, Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType));
return indexInfo.type;
}
return undefined;
}
errorIfWritingToReadonlyIndex(indexInfo);
return indexInfo.type;
}
if (indexType.flags & TypeFlags.Never) {
@ -10126,7 +10151,7 @@ namespace ts {
if (objectType.symbol === globalThisSymbol && propName !== undefined && globalThisSymbol.exports!.has(propName) && (globalThisSymbol.exports!.get(propName)!.flags & SymbolFlags.BlockScoped)) {
error(accessExpression, Diagnostics.Property_0_does_not_exist_on_type_1, unescapeLeadingUnderscores(propName), typeToString(objectType));
}
else if (noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors) {
else if (noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors && !suppressNoImplicitAnyError) {
if (propName !== undefined && typeHasStaticProperty(propName, objectType)) {
error(accessExpression, Diagnostics.Property_0_is_a_static_member_of_type_1, propName as string, typeToString(objectType));
}
@ -10146,7 +10171,29 @@ namespace ts {
error(accessExpression, Diagnostics.Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_Did_you_mean_to_call_1, typeToString(objectType), suggestion);
}
else {
error(accessExpression, Diagnostics.Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature, typeToString(objectType));
let errorInfo: DiagnosticMessageChain | undefined;
if (indexType.flags & TypeFlags.EnumLiteral) {
errorInfo = chainDiagnosticMessages(/* details */ undefined, Diagnostics.Property_0_does_not_exist_on_type_1, "[" + typeToString(indexType) + "]", typeToString(objectType));
}
else if (indexType.flags & TypeFlags.UniqueESSymbol) {
const symbolName = getFullyQualifiedName((indexType as UniqueESSymbolType).symbol, accessExpression);
errorInfo = chainDiagnosticMessages(/* details */ undefined, Diagnostics.Property_0_does_not_exist_on_type_1, "[" + symbolName + "]", typeToString(objectType));
}
else if (indexType.flags & TypeFlags.StringLiteral) {
errorInfo = chainDiagnosticMessages(/* details */ undefined, Diagnostics.Property_0_does_not_exist_on_type_1, (indexType as StringLiteralType).value, typeToString(objectType));
}
else if (indexType.flags & TypeFlags.NumberLiteral) {
errorInfo = chainDiagnosticMessages(/* details */ undefined, Diagnostics.Property_0_does_not_exist_on_type_1, (indexType as NumberLiteralType).value, typeToString(objectType));
}
else if (indexType.flags & (TypeFlags.Number | TypeFlags.String)) {
errorInfo = chainDiagnosticMessages(/* details */ undefined, Diagnostics.No_index_signature_with_a_parameter_of_type_0_was_found_on_type_1, typeToString(indexType), typeToString(objectType));
}
errorInfo = chainDiagnosticMessages(
errorInfo,
Diagnostics.Element_implicitly_has_an_any_type_because_expression_of_type_0_can_t_be_used_to_index_type_1, typeToString(fullIndexType), typeToString(objectType)
);
diagnostics.add(createDiagnosticForNodeFromMessageChain(accessExpression, errorInfo));
}
}
}
@ -10173,6 +10220,12 @@ namespace ts {
return indexType;
}
return undefined;
function errorIfWritingToReadonlyIndex(indexInfo: IndexInfo | undefined): void {
if (indexInfo && indexInfo.isReadonly && accessExpression && (isAssignmentTarget(accessExpression) || isDeleteTarget(accessExpression))) {
error(accessExpression, Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType));
}
}
}
function getIndexNodeForAccessExpression(accessNode: ElementAccessExpression | IndexedAccessTypeNode | PropertyName | BindingName | SyntheticExpression) {
@ -10193,6 +10246,10 @@ namespace ts {
return maybeTypeOfKind(type, TypeFlags.InstantiableNonPrimitive | TypeFlags.Index);
}
function isThisTypeParameter(type: Type): boolean {
return !!(type.flags & TypeFlags.TypeParameter && (<TypeParameter>type).isThisType);
}
function getSimplifiedType(type: Type, writing: boolean): Type {
return type.flags & TypeFlags.IndexedAccess ? getSimplifiedIndexedAccessType(<IndexedAccessType>type, writing) :
type.flags & TypeFlags.Conditional ? getSimplifiedConditionalType(<ConditionalType>type, writing) :
@ -10335,7 +10392,7 @@ namespace ts {
const propTypes: Type[] = [];
let wasMissingProp = false;
for (const t of (<UnionType>indexType).types) {
const propType = getPropertyTypeForIndexType(objectType, apparentObjectType, t, accessNode, accessFlags);
const propType = getPropertyTypeForIndexType(objectType, apparentObjectType, t, indexType, wasMissingProp, accessNode, accessFlags);
if (propType) {
propTypes.push(propType);
}
@ -10353,7 +10410,7 @@ namespace ts {
}
return accessFlags & AccessFlags.Writing ? getIntersectionType(propTypes) : getUnionType(propTypes);
}
return getPropertyTypeForIndexType(objectType, apparentObjectType, indexType, accessNode, accessFlags | AccessFlags.CacheSymbol);
return getPropertyTypeForIndexType(objectType, apparentObjectType, indexType, indexType, /* supressNoImplicitAnyError */ false, accessNode, accessFlags | AccessFlags.CacheSymbol);
}
function getTypeFromIndexedAccessTypeNode(node: IndexedAccessTypeNode) {
@ -13042,8 +13099,7 @@ namespace ts {
}
// A type S is assignable to keyof T if S is assignable to keyof C, where C is the
// simplified form of T or, if T doesn't simplify, the constraint of T.
const simplified = getSimplifiedType((<IndexType>target).type, /*writing*/ false);
const constraint = simplified !== (<IndexType>target).type ? simplified : getConstraintOfType((<IndexType>target).type);
const constraint = getSimplifiedTypeOrConstraint((<IndexType>target).type);
if (constraint) {
// We require Ternary.True here such that circular constraints don't cause
// false positives. For example, given 'T extends { [K in keyof T]: string }',
@ -16772,7 +16828,7 @@ namespace ts {
}
function narrowByInKeyword(type: Type, literal: LiteralExpression, assumeTrue: boolean) {
if ((type.flags & (TypeFlags.Union | TypeFlags.Object)) || (type.flags & TypeFlags.TypeParameter && (type as TypeParameter).isThisType)) {
if (type.flags & (TypeFlags.Union | TypeFlags.Object) || isThisTypeParameter(type)) {
const propName = escapeLeadingUnderscores(literal.text);
return filterType(type, t => isTypePresencePossible(t, propName, assumeTrue));
}
@ -20092,7 +20148,7 @@ namespace ts {
return anyType;
}
if (right.escapedText && !checkAndReportErrorForExtendingInterface(node)) {
reportNonexistentProperty(right, leftType.flags & TypeFlags.TypeParameter && (leftType as TypeParameter).isThisType ? apparentType : leftType);
reportNonexistentProperty(right, isThisTypeParameter(leftType) ? apparentType : leftType);
}
return errorType;
}
@ -20496,7 +20552,7 @@ namespace ts {
const effectiveIndexType = isForInVariableForNumericPropertyNames(indexExpression) ? numberType : indexType;
const accessFlags = isAssignmentTarget(node) ?
AccessFlags.Writing | (isGenericObjectType(objectType) ? AccessFlags.NoIndexSignatures : 0) :
AccessFlags.Writing | (isGenericObjectType(objectType) && !isThisTypeParameter(objectType) ? AccessFlags.NoIndexSignatures : 0) :
AccessFlags.None;
const indexedAccessType = getIndexedAccessTypeOrUndefined(objectType, effectiveIndexType, node, accessFlags) || errorType;
return checkIndexedAccessIndexType(indexedAccessType, node);
@ -23351,14 +23407,16 @@ namespace ts {
if (strictNullChecks && properties.length === 0) {
return checkNonNullType(sourceType, node);
}
for (const p of properties) {
checkObjectLiteralDestructuringPropertyAssignment(sourceType, p, properties, rightIsThis);
for (let i = 0; i < properties.length; i++) {
checkObjectLiteralDestructuringPropertyAssignment(node, sourceType, i, properties, rightIsThis);
}
return sourceType;
}
/** Note: If property cannot be a SpreadAssignment, then allProperties does not need to be provided */
function checkObjectLiteralDestructuringPropertyAssignment(objectLiteralType: Type, property: ObjectLiteralElementLike, allProperties?: NodeArray<ObjectLiteralElementLike>, rightIsThis = false) {
function checkObjectLiteralDestructuringPropertyAssignment(node: ObjectLiteralExpression, objectLiteralType: Type, propertyIndex: number, allProperties?: NodeArray<ObjectLiteralElementLike>, rightIsThis = false) {
const properties = node.properties;
const property = properties[propertyIndex];
if (property.kind === SyntaxKind.PropertyAssignment || property.kind === SyntaxKind.ShorthandPropertyAssignment) {
const name = property.name;
const exprType = getLiteralTypeFromPropertyName(name);
@ -23375,18 +23433,25 @@ namespace ts {
return checkDestructuringAssignment(property.kind === SyntaxKind.ShorthandPropertyAssignment ? property : property.initializer, type);
}
else if (property.kind === SyntaxKind.SpreadAssignment) {
if (languageVersion < ScriptTarget.ESNext) {
checkExternalEmitHelpers(property, ExternalEmitHelpers.Rest);
if (propertyIndex < properties.length - 1) {
error(property, Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern);
}
const nonRestNames: PropertyName[] = [];
if (allProperties) {
for (let i = 0; i < allProperties.length - 1; i++) {
nonRestNames.push(allProperties[i].name!);
else {
if (languageVersion < ScriptTarget.ESNext) {
checkExternalEmitHelpers(property, ExternalEmitHelpers.Rest);
}
const nonRestNames: PropertyName[] = [];
if (allProperties) {
for (const otherProperty of allProperties) {
if (!isSpreadAssignment(otherProperty)) {
nonRestNames.push(otherProperty.name);
}
}
}
const type = getRestType(objectLiteralType, nonRestNames, objectLiteralType.symbol);
checkGrammarForDisallowedTrailingComma(allProperties, Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma);
return checkDestructuringAssignment(property.expression, type);
}
const type = getRestType(objectLiteralType, nonRestNames, objectLiteralType.symbol);
checkGrammarForDisallowedTrailingComma(allProperties, Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma);
return checkDestructuringAssignment(property.expression, type);
}
else {
error(property, Diagnostics.Property_assignment_expected);
@ -25517,7 +25582,7 @@ namespace ts {
case SyntaxKind.ImportSpecifier: // https://github.com/Microsoft/TypeScript/pull/7591
return DeclarationSpaces.ExportValue;
default:
return Debug.fail(Debug.showSyntaxKind(d));
return Debug.failBadSyntaxKind(d);
}
}
}
@ -26820,7 +26885,7 @@ namespace ts {
if (type !== errorType && declarationType !== errorType &&
!isTypeIdenticalTo(type, declarationType) &&
!(symbol.flags & SymbolFlags.Assignment)) {
errorNextVariableOrPropertyDeclarationMustHaveSameType(type, node, declarationType);
errorNextVariableOrPropertyDeclarationMustHaveSameType(symbol.valueDeclaration, type, node, declarationType);
}
if (node.initializer) {
checkTypeAssignableToAndOptionallyElaborate(checkExpressionCached(node.initializer), declarationType, node, node.initializer, /*headMessage*/ undefined);
@ -26840,17 +26905,24 @@ namespace ts {
}
}
function errorNextVariableOrPropertyDeclarationMustHaveSameType(firstType: Type, nextDeclaration: Declaration, nextType: Type): void {
function errorNextVariableOrPropertyDeclarationMustHaveSameType(firstDeclaration: Declaration | undefined, firstType: Type, nextDeclaration: Declaration, nextType: Type): void {
const nextDeclarationName = getNameOfDeclaration(nextDeclaration);
const message = nextDeclaration.kind === SyntaxKind.PropertyDeclaration || nextDeclaration.kind === SyntaxKind.PropertySignature
? Diagnostics.Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_type_2
: Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2;
error(
const declName = declarationNameToString(nextDeclarationName);
const err = error(
nextDeclarationName,
message,
declarationNameToString(nextDeclarationName),
declName,
typeToString(firstType),
typeToString(nextType));
typeToString(nextType)
);
if (firstDeclaration) {
addRelatedInfo(err,
createDiagnosticForNode(firstDeclaration, Diagnostics._0_was_also_declared_here, declName)
);
}
}
function areDeclarationFlagsIdentical(left: Declaration, right: Declaration) {
@ -29920,7 +29992,7 @@ namespace ts {
// }
// [ a ] from
// [a] = [ some array ...]
function getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr: Expression): Type {
function getTypeOfAssignmentPattern(expr: AssignmentPattern): Type | undefined {
Debug.assert(expr.kind === SyntaxKind.ObjectLiteralExpression || expr.kind === SyntaxKind.ArrayLiteralExpression);
// If this is from "for of"
// for ( { a } of elems) {
@ -29938,16 +30010,17 @@ namespace ts {
// If this is from nested object binding pattern
// for ({ skills: { primary, secondary } } = multiRobot, i = 0; i < 1; i++) {
if (expr.parent.kind === SyntaxKind.PropertyAssignment) {
const typeOfParentObjectLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(<Expression>expr.parent.parent);
return checkObjectLiteralDestructuringPropertyAssignment(typeOfParentObjectLiteral || errorType, <ObjectLiteralElementLike>expr.parent)!; // TODO: GH#18217
const node = cast(expr.parent.parent, isObjectLiteralExpression);
const typeOfParentObjectLiteral = getTypeOfAssignmentPattern(node) || errorType;
const propertyIndex = indexOfNode(node.properties, expr.parent);
return checkObjectLiteralDestructuringPropertyAssignment(node, typeOfParentObjectLiteral, propertyIndex);
}
// Array literal assignment - array destructuring pattern
Debug.assert(expr.parent.kind === SyntaxKind.ArrayLiteralExpression);
const node = cast(expr.parent, isArrayLiteralExpression);
// [{ property1: p1, property2 }] = elems;
const typeOfArrayLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(<Expression>expr.parent);
const elementType = checkIteratedTypeOrElementType(typeOfArrayLiteral || errorType, expr.parent, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || errorType;
return checkArrayLiteralDestructuringElementAssignment(<ArrayLiteralExpression>expr.parent, typeOfArrayLiteral,
(<ArrayLiteralExpression>expr.parent).elements.indexOf(expr), elementType || errorType)!; // TODO: GH#18217
const typeOfArrayLiteral = getTypeOfAssignmentPattern(node) || errorType;
const elementType = checkIteratedTypeOrElementType(typeOfArrayLiteral, expr.parent, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || errorType;
return checkArrayLiteralDestructuringElementAssignment(node, typeOfArrayLiteral, node.elements.indexOf(expr), elementType);
}
// Gets the property symbol corresponding to the property in destructuring assignment
@ -29958,7 +30031,7 @@ namespace ts {
// [a] = [ property1, property2 ]
function getPropertySymbolOfDestructuringAssignment(location: Identifier) {
// Get the type of the object or array literal and then look for property of given name in the type
const typeOfObjectLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(<Expression>location.parent.parent);
const typeOfObjectLiteral = getTypeOfAssignmentPattern(cast(location.parent.parent, isAssignmentPattern));
return typeOfObjectLiteral && getPropertyOfType(typeOfObjectLiteral, location.escapedText);
}
@ -30143,12 +30216,17 @@ namespace ts {
return undefined;
}
function isSymbolOfDestructuredElementOfCatchBinding(symbol: Symbol) {
return isBindingElement(symbol.valueDeclaration)
&& walkUpBindingElementsAndPatterns(symbol.valueDeclaration).parent.kind === SyntaxKind.CatchClause;
}
function isSymbolOfDeclarationWithCollidingName(symbol: Symbol): boolean {
if (symbol.flags & SymbolFlags.BlockScoped && !isSourceFile(symbol.valueDeclaration)) {
const links = getSymbolLinks(symbol);
if (links.isDeclarationWithCollidingName === undefined) {
const container = getEnclosingBlockScopeContainer(symbol.valueDeclaration);
if (isStatementWithLocals(container)) {
if (isStatementWithLocals(container) || isSymbolOfDestructuredElementOfCatchBinding(symbol)) {
const nodeLinks = getNodeLinks(symbol.valueDeclaration);
if (resolveName(container.parent, symbol.escapedName, SymbolFlags.Value, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)) {
// redeclaration - always should be renamed

View File

@ -2361,7 +2361,7 @@ namespace ts {
if (!host.fileExists(extendedConfigPath) && !endsWith(extendedConfigPath, Extension.Json)) {
extendedConfigPath = `${extendedConfigPath}.json`;
if (!host.fileExists(extendedConfigPath)) {
errors.push(createDiagnostic(Diagnostics.File_0_does_not_exist, extendedConfig));
errors.push(createDiagnostic(Diagnostics.File_0_not_found, extendedConfig));
return undefined;
}
}
@ -2372,7 +2372,7 @@ namespace ts {
if (resolved.resolvedModule) {
return resolved.resolvedModule.resolvedFileName;
}
errors.push(createDiagnostic(Diagnostics.File_0_does_not_exist, extendedConfig));
errors.push(createDiagnostic(Diagnostics.File_0_not_found, extendedConfig));
return undefined;
}

View File

@ -1686,89 +1686,6 @@ namespace ts {
export type AnyFunction = (...args: never[]) => void;
export type AnyConstructor = new (...args: unknown[]) => unknown;
export namespace Debug {
export let currentAssertionLevel = AssertionLevel.None;
export let isDebugging = false;
export function shouldAssert(level: AssertionLevel): boolean {
return currentAssertionLevel >= level;
}
export function assert(expression: boolean, message?: string, verboseDebugInfo?: string | (() => string), stackCrawlMark?: AnyFunction): void {
if (!expression) {
if (verboseDebugInfo) {
message += "\r\nVerbose Debug Information: " + (typeof verboseDebugInfo === "string" ? verboseDebugInfo : verboseDebugInfo());
}
fail(message ? "False expression: " + message : "False expression.", stackCrawlMark || assert);
}
}
export function assertEqual<T>(a: T, b: T, msg?: string, msg2?: string): void {
if (a !== b) {
const message = msg ? msg2 ? `${msg} ${msg2}` : msg : "";
fail(`Expected ${a} === ${b}. ${message}`);
}
}
export function assertLessThan(a: number, b: number, msg?: string): void {
if (a >= b) {
fail(`Expected ${a} < ${b}. ${msg || ""}`);
}
}
export function assertLessThanOrEqual(a: number, b: number): void {
if (a > b) {
fail(`Expected ${a} <= ${b}`);
}
}
export function assertGreaterThanOrEqual(a: number, b: number): void {
if (a < b) {
fail(`Expected ${a} >= ${b}`);
}
}
export function fail(message?: string, stackCrawlMark?: AnyFunction): never {
debugger;
const e = new Error(message ? `Debug Failure. ${message}` : "Debug Failure.");
if ((<any>Error).captureStackTrace) {
(<any>Error).captureStackTrace(e, stackCrawlMark || fail);
}
throw e;
}
export function assertDefined<T>(value: T | null | undefined, message?: string): T {
if (value === undefined || value === null) return fail(message);
return value;
}
export function assertEachDefined<T, A extends ReadonlyArray<T>>(value: A, message?: string): A {
for (const v of value) {
assertDefined(v, message);
}
return value;
}
export function assertNever(member: never, message = "Illegal value:", stackCrawlMark?: AnyFunction): never {
const detail = typeof member === "object" && "kind" in member && "pos" in member ? "SyntaxKind: " + showSyntaxKind(member as Node) : JSON.stringify(member);
return fail(`${message} ${detail}`, stackCrawlMark || assertNever);
}
export function getFunctionName(func: AnyFunction) {
if (typeof func !== "function") {
return "";
}
else if (func.hasOwnProperty("name")) {
return (<any>func).name;
}
else {
const text = Function.prototype.toString.call(func);
const match = /^function\s+([\w\$]+)\s*\(/.exec(text);
return match ? match[1] : "";
}
}
}
export function equateValues<T>(a: T, b: T) {
return a === b;
}

261
src/compiler/debug.ts Normal file
View File

@ -0,0 +1,261 @@
/* @internal */
namespace ts {
export namespace Debug {
export let currentAssertionLevel = AssertionLevel.None;
export let isDebugging = false;
export function shouldAssert(level: AssertionLevel): boolean {
return currentAssertionLevel >= level;
}
export function assert(expression: boolean, message?: string, verboseDebugInfo?: string | (() => string), stackCrawlMark?: AnyFunction): void {
if (!expression) {
if (verboseDebugInfo) {
message += "\r\nVerbose Debug Information: " + (typeof verboseDebugInfo === "string" ? verboseDebugInfo : verboseDebugInfo());
}
fail(message ? "False expression: " + message : "False expression.", stackCrawlMark || assert);
}
}
export function assertEqual<T>(a: T, b: T, msg?: string, msg2?: string): void {
if (a !== b) {
const message = msg ? msg2 ? `${msg} ${msg2}` : msg : "";
fail(`Expected ${a} === ${b}. ${message}`);
}
}
export function assertLessThan(a: number, b: number, msg?: string): void {
if (a >= b) {
fail(`Expected ${a} < ${b}. ${msg || ""}`);
}
}
export function assertLessThanOrEqual(a: number, b: number): void {
if (a > b) {
fail(`Expected ${a} <= ${b}`);
}
}
export function assertGreaterThanOrEqual(a: number, b: number): void {
if (a < b) {
fail(`Expected ${a} >= ${b}`);
}
}
export function fail(message?: string, stackCrawlMark?: AnyFunction): never {
debugger;
const e = new Error(message ? `Debug Failure. ${message}` : "Debug Failure.");
if ((<any>Error).captureStackTrace) {
(<any>Error).captureStackTrace(e, stackCrawlMark || fail);
}
throw e;
}
export function assertDefined<T>(value: T | null | undefined, message?: string): T {
if (value === undefined || value === null) return fail(message);
return value;
}
export function assertEachDefined<T, A extends ReadonlyArray<T>>(value: A, message?: string): A {
for (const v of value) {
assertDefined(v, message);
}
return value;
}
export function assertNever(member: never, message = "Illegal value:", stackCrawlMark?: AnyFunction): never {
const detail = typeof member === "object" && "kind" in member && "pos" in member && formatSyntaxKind ? "SyntaxKind: " + formatSyntaxKind((member as Node).kind) : JSON.stringify(member);
return fail(`${message} ${detail}`, stackCrawlMark || assertNever);
}
export function getFunctionName(func: AnyFunction) {
if (typeof func !== "function") {
return "";
}
else if (func.hasOwnProperty("name")) {
return (<any>func).name;
}
else {
const text = Function.prototype.toString.call(func);
const match = /^function\s+([\w\$]+)\s*\(/.exec(text);
return match ? match[1] : "";
}
}
export function formatSymbol(symbol: Symbol): string {
return `{ name: ${unescapeLeadingUnderscores(symbol.escapedName)}; flags: ${formatSymbolFlags(symbol.flags)}; declarations: ${map(symbol.declarations, node => formatSyntaxKind(node.kind))} }`;
}
/**
* Formats an enum value as a string for debugging and debug assertions.
*/
export function formatEnum(value = 0, enumObject: any, isFlags?: boolean) {
const members = getEnumMembers(enumObject);
if (value === 0) {
return members.length > 0 && members[0][0] === 0 ? members[0][1] : "0";
}
if (isFlags) {
let result = "";
let remainingFlags = value;
for (let i = members.length - 1; i >= 0 && remainingFlags !== 0; i--) {
const [enumValue, enumName] = members[i];
if (enumValue !== 0 && (remainingFlags & enumValue) === enumValue) {
remainingFlags &= ~enumValue;
result = `${enumName}${result ? "|" : ""}${result}`;
}
}
if (remainingFlags === 0) {
return result;
}
}
else {
for (const [enumValue, enumName] of members) {
if (enumValue === value) {
return enumName;
}
}
}
return value.toString();
}
function getEnumMembers(enumObject: any) {
const result: [number, string][] = [];
for (const name in enumObject) {
const value = enumObject[name];
if (typeof value === "number") {
result.push([value, name]);
}
}
return stableSort<[number, string]>(result, (x, y) => compareValues(x[0], y[0]));
}
export function formatSyntaxKind(kind: SyntaxKind | undefined): string {
return formatEnum(kind, (<any>ts).SyntaxKind, /*isFlags*/ false);
}
export function formatNodeFlags(flags: NodeFlags | undefined): string {
return formatEnum(flags, (<any>ts).NodeFlags, /*isFlags*/ true);
}
export function formatModifierFlags(flags: ModifierFlags | undefined): string {
return formatEnum(flags, (<any>ts).ModifierFlags, /*isFlags*/ true);
}
export function formatTransformFlags(flags: TransformFlags | undefined): string {
return formatEnum(flags, (<any>ts).TransformFlags, /*isFlags*/ true);
}
export function formatEmitFlags(flags: EmitFlags | undefined): string {
return formatEnum(flags, (<any>ts).EmitFlags, /*isFlags*/ true);
}
export function formatSymbolFlags(flags: SymbolFlags | undefined): string {
return formatEnum(flags, (<any>ts).SymbolFlags, /*isFlags*/ true);
}
export function formatTypeFlags(flags: TypeFlags | undefined): string {
return formatEnum(flags, (<any>ts).TypeFlags, /*isFlags*/ true);
}
export function formatObjectFlags(flags: ObjectFlags | undefined): string {
return formatEnum(flags, (<any>ts).ObjectFlags, /*isFlags*/ true);
}
export function failBadSyntaxKind(node: Node, message?: string): never {
return fail(
`${message || "Unexpected node."}\r\nNode ${formatSyntaxKind(node.kind)} was unexpected.`,
failBadSyntaxKind);
}
export const assertEachNode = shouldAssert(AssertionLevel.Normal)
? (nodes: Node[], test: (node: Node) => boolean, message?: string): void => assert(
test === undefined || every(nodes, test),
message || "Unexpected node.",
() => `Node array did not pass test '${getFunctionName(test)}'.`,
assertEachNode)
: noop;
export const assertNode = shouldAssert(AssertionLevel.Normal)
? (node: Node | undefined, test: ((node: Node | undefined) => boolean) | undefined, message?: string): void => assert(
test === undefined || test(node),
message || "Unexpected node.",
() => `Node ${formatSyntaxKind(node!.kind)} did not pass test '${getFunctionName(test!)}'.`,
assertNode)
: noop;
export const assertOptionalNode = shouldAssert(AssertionLevel.Normal)
? (node: Node, test: (node: Node) => boolean, message?: string): void => assert(
test === undefined || node === undefined || test(node),
message || "Unexpected node.",
() => `Node ${formatSyntaxKind(node.kind)} did not pass test '${getFunctionName(test)}'.`,
assertOptionalNode)
: noop;
export const assertOptionalToken = shouldAssert(AssertionLevel.Normal)
? (node: Node, kind: SyntaxKind, message?: string): void => assert(
kind === undefined || node === undefined || node.kind === kind,
message || "Unexpected node.",
() => `Node ${formatSyntaxKind(node.kind)} was not a '${formatSyntaxKind(kind)}' token.`,
assertOptionalToken)
: noop;
export const assertMissingNode = shouldAssert(AssertionLevel.Normal)
? (node: Node, message?: string): void => assert(
node === undefined,
message || "Unexpected node.",
() => `Node ${formatSyntaxKind(node.kind)} was unexpected'.`,
assertMissingNode)
: noop;
let isDebugInfoEnabled = false;
/**
* Injects debug information into frequently used types.
*/
export function enableDebugInfo() {
if (isDebugInfoEnabled) return;
// Add additional properties in debug mode to assist with debugging.
Object.defineProperties(objectAllocator.getSymbolConstructor().prototype, {
__debugFlags: { get(this: Symbol) { return formatSymbolFlags(this.flags); } }
});
Object.defineProperties(objectAllocator.getTypeConstructor().prototype, {
__debugFlags: { get(this: Type) { return formatTypeFlags(this.flags); } },
__debugObjectFlags: { get(this: Type) { return this.flags & TypeFlags.Object ? formatObjectFlags((<ObjectType>this).objectFlags) : ""; } },
__debugTypeToString: { value(this: Type) { return this.checker.typeToString(this); } },
});
const nodeConstructors = [
objectAllocator.getNodeConstructor(),
objectAllocator.getIdentifierConstructor(),
objectAllocator.getTokenConstructor(),
objectAllocator.getSourceFileConstructor()
];
for (const ctor of nodeConstructors) {
if (!ctor.prototype.hasOwnProperty("__debugKind")) {
Object.defineProperties(ctor.prototype, {
__debugKind: { get(this: Node) { return formatSyntaxKind(this.kind); } },
__debugNodeFlags: { get(this: Node) { return formatNodeFlags(this.flags); } },
__debugModifierFlags: { get(this: Node) { return formatModifierFlags(getModifierFlagsNoCache(this)); } },
__debugTransformFlags: { get(this: Node) { return formatTransformFlags(this.transformFlags); } },
__debugIsParseTreeNode: { get(this: Node) { return isParseTreeNode(this); } },
__debugEmitFlags: { get(this: Node) { return formatEmitFlags(getEmitFlags(this)); } },
__debugGetText: {
value(this: Node, includeTrivia?: boolean) {
if (nodeIsSynthesized(this)) return "";
const parseNode = getParseTreeNode(this);
const sourceFile = parseNode && getSourceFileOfNode(parseNode);
return sourceFile ? getSourceTextOfNodeFromSourceFile(sourceFile, parseNode, includeTrivia) : "";
}
}
});
}
}
isDebugInfoEnabled = true;
}
}
}

View File

@ -655,7 +655,7 @@
"category": "Error",
"code": 1207
},
"Cannot compile namespaces when the '--isolatedModules' flag is provided.": {
"All files must be modules when the '--isolatedModules' flag is provided.": {
"category": "Error",
"code": 1208
},
@ -3811,10 +3811,6 @@
"category": "Error",
"code": 6189
},
"Found 'package.json' at '{0}'. Package ID is '{1}'.": {
"category": "Message",
"code": 6190
},
"Whether to keep outdated console output in watch mode instead of clearing the screen.": {
"category": "Message",
"code": 6191
@ -3923,6 +3919,18 @@
"category": "Message",
"code": 6217
},
"======== Module name '{0}' was successfully resolved to '{1}' with Package ID '{2}'. ========": {
"category": "Message",
"code": 6218
},
"======== Type reference directive '{0}' was successfully resolved to '{1}' with Package ID '{2}', primary: {3}. ========": {
"category": "Message",
"code": 6219
},
"'package.json' had a falsy '{0}' field.": {
"category": "Message",
"code": 6220
},
"Projects to reference": {
"category": "Message",
@ -4284,6 +4292,14 @@
"category": "Error",
"code": 7052
},
"Element implicitly has an 'any' type because expression of type '{0}' can't be used to index type '{1}'.": {
"category": "Error",
"code": 7053
},
"No index signature with a parameter of type '{0}' was found on type '{1}'.": {
"category": "Error",
"code": 7054
},
"You cannot rename this element.": {
"category": "Error",
"code": 8000
@ -4975,7 +4991,7 @@
"code": 95079
},
"No value exists in scope for the shorthand property '{0}'. Either declare one or provide an initializer." :{
"No value exists in scope for the shorthand property '{0}'. Either declare one or provide an initializer.": {
"category": "Error",
"code": 18004
},

View File

@ -4527,6 +4527,8 @@ namespace ts {
case SyntaxKind.GetAccessor:
case SyntaxKind.SetAccessor:
return generateNameForMethodOrAccessor(<MethodDeclaration | AccessorDeclaration>node);
case SyntaxKind.ComputedPropertyName:
return makeTempVariableName(TempFlags.Auto, /*reserveInNestedScopes*/ true);
default:
return makeTempVariableName(TempFlags.Auto);
}

View File

@ -16,12 +16,23 @@ namespace ts {
push(value: T): void;
}
function withPackageId(packageId: PackageId | undefined, r: PathAndExtension | undefined): Resolved | undefined {
function withPackageId(packageInfo: PackageJsonInfo | undefined, r: PathAndExtension | undefined): Resolved | undefined {
let packageId: PackageId | undefined;
if (r && packageInfo) {
const packageJsonContent = packageInfo.packageJsonContent as PackageJson;
if (typeof packageJsonContent.name === "string" && typeof packageJsonContent.version === "string") {
packageId = {
name: packageJsonContent.name,
subModuleName: r.path.slice(packageInfo.packageDirectory.length + directorySeparator.length),
version: packageJsonContent.version
};
}
}
return r && { path: r.path, extension: r.ext, packageId };
}
function noPackageId(r: PathAndExtension | undefined): Resolved | undefined {
return withPackageId(/*packageId*/ undefined, r);
return withPackageId(/*packageInfo*/ undefined, r);
}
function removeIgnoredPackageId(r: Resolved | undefined): PathAndExtension | undefined {
@ -130,7 +141,15 @@ namespace ts {
function readPackageJsonPathField<K extends "typings" | "types" | "main" | "tsconfig">(jsonContent: PackageJson, fieldName: K, baseDirectory: string, state: ModuleResolutionState): PackageJson[K] | undefined {
const fileName = readPackageJsonField(jsonContent, fieldName, "string", state);
if (fileName === undefined) return;
if (fileName === undefined) {
return;
}
if (!fileName) {
if (state.traceEnabled) {
trace(state.host, Diagnostics.package_json_had_a_falsy_0_field, fieldName);
}
return;
}
const path = normalizePath(combinePaths(baseDirectory, fileName));
if (state.traceEnabled) {
trace(state.host, Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path);
@ -307,7 +326,12 @@ namespace ts {
const { fileName, packageId } = resolved;
const resolvedFileName = options.preserveSymlinks ? fileName : realPath(fileName, host, traceEnabled);
if (traceEnabled) {
trace(host, Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFileName, primary);
if (packageId) {
trace(host, Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_with_Package_ID_2_primary_Colon_3, typeReferenceDirectiveName, resolvedFileName, packageIdToString(packageId), primary);
}
else {
trace(host, Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFileName, primary);
}
}
resolvedTypeReferenceDirective = { primary, resolvedFileName, packageId, isExternalLibraryImport: pathContainsNodeModules(fileName) };
}
@ -663,7 +687,12 @@ namespace ts {
if (traceEnabled) {
if (result.resolvedModule) {
trace(host, Diagnostics.Module_name_0_was_successfully_resolved_to_1, moduleName, result.resolvedModule.resolvedFileName);
if (result.resolvedModule.packageId) {
trace(host, Diagnostics.Module_name_0_was_successfully_resolved_to_1_with_Package_ID_2, moduleName, result.resolvedModule.resolvedFileName, packageIdToString(result.resolvedModule.packageId));
}
else {
trace(host, Diagnostics.Module_name_0_was_successfully_resolved_to_1, moduleName, result.resolvedModule.resolvedFileName);
}
}
else {
trace(host, Diagnostics.Module_name_0_was_not_resolved, moduleName);
@ -968,10 +997,9 @@ namespace ts {
}
const resolvedFromFile = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state);
if (resolvedFromFile) {
const nm = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile) : undefined;
const packageInfo = nm && getPackageJsonInfo(nm.packageDirectory, nm.subModuleName, /*onlyRecordFailures*/ false, state);
const packageId = packageInfo && packageInfo.packageId;
return withPackageId(packageId, resolvedFromFile);
const packageDirectory = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile) : undefined;
const packageInfo = packageDirectory ? getPackageJsonInfo(packageDirectory, /*onlyRecordFailures*/ false, state) : undefined;
return withPackageId(packageInfo, resolvedFromFile);
}
}
if (!onlyRecordFailures) {
@ -998,13 +1026,12 @@ namespace ts {
* (Not neeeded for `loadModuleFromNodeModules` as that looks up the `package.json` as part of resolution.)
*
* packageDirectory is the directory of the package itself.
* subModuleName is the path within the package.
* For `blah/node_modules/foo/index.d.ts` this is { packageDirectory: "foo", subModuleName: "index.d.ts" }. (Part before "/node_modules/" is ignored.)
* For `/node_modules/foo/bar.d.ts` this is { packageDirectory: "foo", subModuleName": "bar/index.d.ts" }.
* For `/node_modules/@types/foo/bar/index.d.ts` this is { packageDirectory: "@types/foo", subModuleName: "bar/index.d.ts" }.
* For `/node_modules/foo/bar/index.d.ts` this is { packageDirectory: "foo", subModuleName": "bar/index.d.ts" }.
* For `blah/node_modules/foo/index.d.ts` this is packageDirectory: "foo"
* For `/node_modules/foo/bar.d.ts` this is packageDirectory: "foo"
* For `/node_modules/@types/foo/bar/index.d.ts` this is packageDirectory: "@types/foo"
* For `/node_modules/foo/bar/index.d.ts` this is packageDirectory: "foo"
*/
function parseNodeModuleFromPath(resolved: PathAndExtension): { packageDirectory: string, subModuleName: string } | undefined {
function parseNodeModuleFromPath(resolved: PathAndExtension): string | undefined {
const path = normalizePath(resolved.path);
const idx = path.lastIndexOf(nodeModulesPathPart);
if (idx === -1) {
@ -1016,9 +1043,7 @@ namespace ts {
if (path.charCodeAt(indexAfterNodeModules) === CharacterCodes.at) {
indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterPackageName);
}
const packageDirectory = path.slice(0, indexAfterPackageName);
const subModuleName = removeExtension(path.slice(indexAfterPackageName + 1), resolved.ext) + Extension.Dts;
return { packageDirectory, subModuleName };
return path.slice(0, indexAfterPackageName);
}
function moveToNextDirectorySeparatorIfAvailable(path: string, prevSeparatorIndex: number): number {
@ -1026,19 +1051,6 @@ namespace ts {
return nextSeparatorIndex === -1 ? prevSeparatorIndex : nextSeparatorIndex;
}
function addExtensionAndIndex(path: string): string {
if (path === "") {
return "index.d.ts";
}
if (endsWith(path, ".d.ts")) {
return path;
}
if (path === "index" || endsWith(path, "/index")) {
return path + ".d.ts";
}
return path + "/index.d.ts";
}
function loadModuleFromFileNoPackageId(extensions: Extensions, candidate: string, onlyRecordFailures: boolean, state: ModuleResolutionState): Resolved | undefined {
return noPackageId(loadModuleFromFile(extensions, candidate, onlyRecordFailures, state));
}
@ -1119,61 +1131,29 @@ namespace ts {
}
function loadNodeModuleFromDirectory(extensions: Extensions, candidate: string, onlyRecordFailures: boolean, state: ModuleResolutionState, considerPackageJson = true) {
const packageInfo = considerPackageJson ? getPackageJsonInfo(candidate, "", onlyRecordFailures, state) : undefined;
const packageId = packageInfo && packageInfo.packageId;
const packageInfo = considerPackageJson ? getPackageJsonInfo(candidate, onlyRecordFailures, state) : undefined;
const packageJsonContent = packageInfo && packageInfo.packageJsonContent;
const versionPaths = packageInfo && packageInfo.versionPaths;
return withPackageId(packageId, loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths));
return withPackageId(packageInfo, loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths));
}
interface PackageJsonInfo {
packageJsonContent: PackageJsonPathFields | undefined;
packageId: PackageId | undefined;
packageDirectory: string;
packageJsonContent: PackageJsonPathFields;
versionPaths: VersionPaths | undefined;
}
function getPackageJsonInfo(packageDirectory: string, subModuleName: string, onlyRecordFailures: boolean, state: ModuleResolutionState): PackageJsonInfo | undefined {
function getPackageJsonInfo(packageDirectory: string, onlyRecordFailures: boolean, state: ModuleResolutionState): PackageJsonInfo | undefined {
const { host, traceEnabled } = state;
const directoryExists = !onlyRecordFailures && directoryProbablyExists(packageDirectory, host);
const packageJsonPath = combinePaths(packageDirectory, "package.json");
if (directoryExists && host.fileExists(packageJsonPath)) {
const packageJsonContent = readJson(packageJsonPath, host) as PackageJson;
if (subModuleName === "") { // looking up the root - need to handle types/typings/main redirects for subModuleName
const path = readPackageJsonTypesFields(packageJsonContent, packageDirectory, state);
if (typeof path === "string") {
subModuleName = addExtensionAndIndex(path.substring(packageDirectory.length + 1));
}
else {
const jsPath = readPackageJsonMainField(packageJsonContent, packageDirectory, state);
if (typeof jsPath === "string" && jsPath.length > packageDirectory.length) {
const potentialSubModule = jsPath.substring(packageDirectory.length + 1);
subModuleName = (forEach(supportedJSExtensions, extension =>
tryRemoveExtension(potentialSubModule, extension)) || potentialSubModule) + Extension.Dts;
}
else {
subModuleName = "index.d.ts";
}
}
}
if (!endsWith(subModuleName, Extension.Dts)) {
subModuleName = addExtensionAndIndex(subModuleName);
}
const versionPaths = readPackageJsonTypesVersionPaths(packageJsonContent, state);
const packageId: PackageId | undefined = typeof packageJsonContent.name === "string" && typeof packageJsonContent.version === "string"
? { name: packageJsonContent.name, subModuleName, version: packageJsonContent.version }
: undefined;
if (traceEnabled) {
if (packageId) {
trace(host, Diagnostics.Found_package_json_at_0_Package_ID_is_1, packageJsonPath, packageIdToString(packageId));
}
else {
trace(host, Diagnostics.Found_package_json_at_0, packageJsonPath);
}
trace(host, Diagnostics.Found_package_json_at_0, packageJsonPath);
}
return { packageJsonContent, packageId, versionPaths };
const versionPaths = readPackageJsonTypesVersionPaths(packageJsonContent, state);
return { packageDirectory, packageJsonContent, versionPaths };
}
else {
if (directoryExists && traceEnabled) {
@ -1328,27 +1308,36 @@ namespace ts {
const candidate = normalizePath(combinePaths(nodeModulesDirectory, moduleName));
// First look for a nested package.json, as in `node_modules/foo/bar/package.json`.
let packageJsonContent: PackageJsonPathFields | undefined;
let packageId: PackageId | undefined;
let versionPaths: VersionPaths | undefined;
const packageInfo = getPackageJsonInfo(candidate, "", !nodeModulesDirectoryExists, state);
let packageInfo = getPackageJsonInfo(candidate, !nodeModulesDirectoryExists, state);
if (packageInfo) {
({ packageJsonContent, packageId, versionPaths } = packageInfo);
const fromFile = loadModuleFromFile(extensions, candidate, !nodeModulesDirectoryExists, state);
if (fromFile) {
return noPackageId(fromFile);
}
const fromDirectory = loadNodeModuleFromDirectoryWorker(extensions, candidate, !nodeModulesDirectoryExists, state, packageJsonContent, versionPaths);
return withPackageId(packageId, fromDirectory);
const fromDirectory = loadNodeModuleFromDirectoryWorker(
extensions,
candidate,
!nodeModulesDirectoryExists,
state,
packageInfo.packageJsonContent,
packageInfo.versionPaths
);
return withPackageId(packageInfo, fromDirectory);
}
const loader: ResolutionKindSpecificLoader = (extensions, candidate, onlyRecordFailures, state) => {
const pathAndExtension =
loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) ||
loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths);
return withPackageId(packageId, pathAndExtension);
loadNodeModuleFromDirectoryWorker(
extensions,
candidate,
onlyRecordFailures,
state,
packageInfo && packageInfo.packageJsonContent,
packageInfo && packageInfo.versionPaths
);
return withPackageId(packageInfo, pathAndExtension);
};
const { packageName, rest } = parsePackageName(moduleName);
@ -1356,14 +1345,13 @@ namespace ts {
const packageDirectory = combinePaths(nodeModulesDirectory, packageName);
// Don't use a "types" or "main" from here because we're not loading the root, but a subdirectory -- just here for the packageId and path mappings.
const packageInfo = getPackageJsonInfo(packageDirectory, rest, !nodeModulesDirectoryExists, state);
if (packageInfo) ({ packageId, versionPaths } = packageInfo);
if (versionPaths) {
packageInfo = getPackageJsonInfo(packageDirectory, !nodeModulesDirectoryExists, state);
if (packageInfo && packageInfo.versionPaths) {
if (state.traceEnabled) {
trace(state.host, Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, versionPaths.version, version, rest);
trace(state.host, Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, packageInfo.versionPaths.version, version, rest);
}
const packageDirectoryExists = nodeModulesDirectoryExists && directoryProbablyExists(packageDirectory, state.host);
const fromPaths = tryLoadModuleUsingPaths(extensions, rest, packageDirectory, versionPaths.paths, loader, !packageDirectoryExists, state);
const fromPaths = tryLoadModuleUsingPaths(extensions, rest, packageDirectory, packageInfo.versionPaths.paths, loader, !packageDirectoryExists, state);
if (fromPaths) {
return fromPaths.value;
}

View File

@ -175,9 +175,9 @@ namespace ts.moduleSpecifiers {
function discoverProbableSymlinks(files: ReadonlyArray<SourceFile>, getCanonicalFileName: GetCanonicalFileName, cwd: string): ReadonlyMap<string> {
const result = createMap<string>();
const symlinks = mapDefined(files, sf =>
sf.resolvedModules && firstDefinedIterator(sf.resolvedModules.values(), res =>
res && res.originalPath && res.resolvedFileName !== res.originalPath ? [res.resolvedFileName, res.originalPath] : undefined));
const symlinks = flatten<readonly [string, string]>(mapDefined(files, sf =>
sf.resolvedModules && compact(arrayFrom(mapIterator(sf.resolvedModules.values(), res =>
res && res.originalPath && res.resolvedFileName !== res.originalPath ? [res.resolvedFileName, res.originalPath] as const : undefined)))));
for (const [resolvedPath, originalPath] of symlinks) {
const [commonResolved, commonOriginal] = guessDirectorySymlink(resolvedPath, originalPath, cwd, getCanonicalFileName);
result.set(commonOriginal, commonResolved);

View File

@ -2232,7 +2232,10 @@ namespace ts {
if (isRedirect) {
inputName = getProjectReferenceRedirect(fileName) || fileName;
}
if (getNormalizedAbsolutePath(checkedName, currentDirectory) !== getNormalizedAbsolutePath(inputName, currentDirectory)) {
// Check if it differs only in drive letters its ok to ignore that error:
const checkedAbsolutePath = getNormalizedAbsolutePathWithoutRoot(checkedName, currentDirectory);
const inputAbsolutePath = getNormalizedAbsolutePathWithoutRoot(inputName, currentDirectory);
if (checkedAbsolutePath !== inputAbsolutePath) {
reportFileNamesDifferOnlyInCasingError(inputName, checkedName, refFile, refPos, refEnd);
}
}
@ -2855,10 +2858,10 @@ namespace ts {
createDiagnosticForOptionName(Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher, "isolatedModules", "target");
}
const firstNonExternalModuleSourceFile = find(files, f => !isExternalModule(f) && !f.isDeclarationFile && f.scriptKind !== ScriptKind.JSON);
const firstNonExternalModuleSourceFile = find(files, f => !isExternalModule(f) && !isSourceFileJS(f) && !f.isDeclarationFile && f.scriptKind !== ScriptKind.JSON);
if (firstNonExternalModuleSourceFile) {
const span = getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile);
programDiagnostics.add(createFileDiagnostic(firstNonExternalModuleSourceFile, span.start, span.length, Diagnostics.Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided));
programDiagnostics.add(createFileDiagnostic(firstNonExternalModuleSourceFile, span.start, span.length, Diagnostics.All_files_must_be_modules_when_the_isolatedModules_flag_is_provided));
}
}
else if (firstNonAmbientExternalModuleSourceFile && languageVersion < ScriptTarget.ES2015 && options.module === ModuleKind.None) {

View File

@ -145,7 +145,7 @@ namespace ts {
loopOutParameters: LoopOutParameter[];
}
type LoopConverter = (node: IterationStatement, outermostLabeledStatement: LabeledStatement | undefined, convertedLoopBodyStatements: Statement[] | undefined) => Statement;
type LoopConverter = (node: IterationStatement, outermostLabeledStatement: LabeledStatement | undefined, convertedLoopBodyStatements: Statement[] | undefined, ancestorFacts: HierarchyFacts) => Statement;
// Facts we track as we traverse the tree
const enum HierarchyFacts {
@ -163,11 +163,12 @@ namespace ts {
ExportedVariableStatement = 1 << 5, // Enclosed in an exported variable statement in the current scope
TopLevel = 1 << 6, // Enclosing block-scoped container is a top-level container
Block = 1 << 7, // Enclosing block-scoped container is a Block
IterationStatement = 1 << 8, // Enclosed in an IterationStatement
IterationStatement = 1 << 8, // Immediately enclosed in an IterationStatement
IterationStatementBlock = 1 << 9, // Enclosing Block is enclosed in an IterationStatement
ForStatement = 1 << 10, // Enclosing block-scoped container is a ForStatement
ForInOrForOfStatement = 1 << 11, // Enclosing block-scoped container is a ForInStatement or ForOfStatement
ConstructorWithCapturedSuper = 1 << 12, // Enclosed in a constructor that captures 'this' for use with 'super'
IterationContainer = 1 << 10, // Enclosed in an outer IterationStatement
ForStatement = 1 << 11, // Enclosing block-scoped container is a ForStatement
ForInOrForOfStatement = 1 << 12, // Enclosing block-scoped container is a ForInStatement or ForOfStatement
ConstructorWithCapturedSuper = 1 << 13, // Enclosed in a constructor that captures 'this' for use with 'super'
// NOTE: do not add more ancestor flags without also updating AncestorFactsMask below.
// NOTE: when adding a new ancestor flag, be sure to update the subtree flags below.
@ -184,11 +185,11 @@ namespace ts {
// A source file is a top-level block scope.
SourceFileIncludes = TopLevel,
SourceFileExcludes = BlockScopeExcludes & ~TopLevel,
SourceFileExcludes = BlockScopeExcludes & ~TopLevel | IterationContainer,
// Functions, methods, and accessors are both new lexical scopes and new block scopes.
FunctionIncludes = Function | TopLevel,
FunctionExcludes = BlockScopeExcludes & ~TopLevel | ArrowFunction | AsyncFunctionBody | CapturesThis | NonStaticClassElement | ConstructorWithCapturedSuper,
FunctionExcludes = BlockScopeExcludes & ~TopLevel | ArrowFunction | AsyncFunctionBody | CapturesThis | NonStaticClassElement | ConstructorWithCapturedSuper | IterationContainer,
AsyncFunctionBodyIncludes = FunctionIncludes | AsyncFunctionBody,
AsyncFunctionBodyExcludes = FunctionExcludes & ~NonStaticClassElement,
@ -205,16 +206,16 @@ namespace ts {
// 'do' and 'while' statements are not block scopes. We track that the subtree is contained
// within an IterationStatement to indicate whether the embedded statement is an
// IterationStatementBlock.
DoOrWhileStatementIncludes = IterationStatement,
DoOrWhileStatementIncludes = IterationStatement | IterationContainer,
DoOrWhileStatementExcludes = None,
// 'for' statements are new block scopes and have special handling for 'let' declarations.
ForStatementIncludes = IterationStatement | ForStatement,
ForStatementIncludes = IterationStatement | ForStatement | IterationContainer,
ForStatementExcludes = BlockScopeExcludes & ~ForStatement,
// 'for-in' and 'for-of' statements are new block scopes and have special handling for
// 'let' declarations.
ForInOrForOfStatementIncludes = IterationStatement | ForInOrForOfStatement,
ForInOrForOfStatementIncludes = IterationStatement | ForInOrForOfStatement | IterationContainer,
ForInOrForOfStatementExcludes = BlockScopeExcludes & ~ForInOrForOfStatement,
// Blocks (other than function bodies) are new block scopes.
@ -228,8 +229,8 @@ namespace ts {
// Subtree facts
//
NewTarget = 1 << 13, // Contains a 'new.target' meta-property
CapturedLexicalThis = 1 << 14, // Contains a lexical `this` reference captured by an arrow function.
NewTarget = 1 << 14, // Contains a 'new.target' meta-property
CapturedLexicalThis = 1 << 15, // Contains a lexical `this` reference captured by an arrow function.
//
// Subtree masks
@ -2227,7 +2228,7 @@ namespace ts {
function visitIterationStatementWithFacts(excludeFacts: HierarchyFacts, includeFacts: HierarchyFacts, node: IterationStatement, outermostLabeledStatement: LabeledStatement | undefined, convert?: LoopConverter) {
const ancestorFacts = enterSubtree(excludeFacts, includeFacts);
const updated = convertIterationStatementBodyIfNecessary(node, outermostLabeledStatement, convert);
const updated = convertIterationStatementBodyIfNecessary(node, outermostLabeledStatement, ancestorFacts, convert);
exitSubtree(ancestorFacts, HierarchyFacts.None, HierarchyFacts.None);
return updated;
}
@ -2434,7 +2435,7 @@ namespace ts {
return restoreEnclosingLabel(forStatement, outermostLabeledStatement, convertedLoopState && resetLabel);
}
function convertForOfStatementForIterable(node: ForOfStatement, outermostLabeledStatement: LabeledStatement, convertedLoopBodyStatements: Statement[]): Statement {
function convertForOfStatementForIterable(node: ForOfStatement, outermostLabeledStatement: LabeledStatement, convertedLoopBodyStatements: Statement[], ancestorFacts: HierarchyFacts): Statement {
const expression = visitNode(node.expression, visitor, isExpression);
const iterator = isIdentifier(expression) ? getGeneratedNameForNode(expression) : createTempVariable(/*recordTempVariable*/ undefined);
const result = isIdentifier(expression) ? getGeneratedNameForNode(iterator) : createTempVariable(/*recordTempVariable*/ undefined);
@ -2447,13 +2448,18 @@ namespace ts {
hoistVariableDeclaration(errorRecord);
hoistVariableDeclaration(returnMethod);
// if we are enclosed in an outer loop ensure we reset 'errorRecord' per each iteration
const initializer = ancestorFacts & HierarchyFacts.IterationContainer
? inlineExpressions([createAssignment(errorRecord, createVoidZero()), values])
: values;
const forStatement = setEmitFlags(
setTextRange(
createFor(
/*initializer*/ setEmitFlags(
setTextRange(
createVariableDeclarationList([
setTextRange(createVariableDeclaration(iterator, /*type*/ undefined, values), node.expression),
setTextRange(createVariableDeclaration(iterator, /*type*/ undefined, initializer), node.expression),
createVariableDeclaration(result, /*type*/ undefined, next)
]),
node.expression
@ -2665,7 +2671,7 @@ namespace ts {
}
}
function convertIterationStatementBodyIfNecessary(node: IterationStatement, outermostLabeledStatement: LabeledStatement | undefined, convert?: LoopConverter): VisitResult<Statement> {
function convertIterationStatementBodyIfNecessary(node: IterationStatement, outermostLabeledStatement: LabeledStatement | undefined, ancestorFacts: HierarchyFacts, convert?: LoopConverter): VisitResult<Statement> {
if (!shouldConvertIterationStatement(node)) {
let saveAllowedNonLabeledJumps: Jump | undefined;
if (convertedLoopState) {
@ -2676,7 +2682,7 @@ namespace ts {
}
const result = convert
? convert(node, outermostLabeledStatement, /*convertedLoopBodyStatements*/ undefined)
? convert(node, outermostLabeledStatement, /*convertedLoopBodyStatements*/ undefined, ancestorFacts)
: restoreEnclosingLabel(visitEachChild(node, visitor, context), outermostLabeledStatement, convertedLoopState && resetLabel);
if (convertedLoopState) {
@ -2708,7 +2714,7 @@ namespace ts {
let loop: Statement;
if (bodyFunction) {
if (convert) {
loop = convert(node, outermostLabeledStatement, bodyFunction.part);
loop = convert(node, outermostLabeledStatement, bodyFunction.part, ancestorFacts);
}
else {
const clone = convertIterationStatementCore(node, initializerFunction, createBlock(bodyFunction.part, /*multiLine*/ true));

View File

@ -77,6 +77,8 @@ namespace ts {
return visitObjectLiteralExpression(node as ObjectLiteralExpression);
case SyntaxKind.BinaryExpression:
return visitBinaryExpression(node as BinaryExpression, noDestructuringValue);
case SyntaxKind.CatchClause:
return visitCatchClause(node as CatchClause);
case SyntaxKind.VariableDeclaration:
return visitVariableDeclaration(node as VariableDeclaration);
case SyntaxKind.ForOfStatement:
@ -272,6 +274,28 @@ namespace ts {
return visitEachChild(node, visitor, context);
}
function visitCatchClause(node: CatchClause) {
if (node.variableDeclaration &&
isBindingPattern(node.variableDeclaration.name) &&
node.variableDeclaration.name.transformFlags & TransformFlags.ContainsObjectRestOrSpread) {
const name = getGeneratedNameForNode(node.variableDeclaration.name);
const updatedDecl = updateVariableDeclaration(node.variableDeclaration, node.variableDeclaration.name, /*type*/ undefined, name);
const visitedBindings = flattenDestructuringBinding(updatedDecl, visitor, context, FlattenLevel.ObjectRest);
let block = visitNode(node.block, visitor, isBlock);
if (some(visitedBindings)) {
block = updateBlock(block, [
createVariableStatement(/*modifiers*/ undefined, visitedBindings),
...block.statements,
]);
}
return updateCatchClause(
node,
updateVariableDeclaration(node.variableDeclaration, name, /*type*/ undefined, /*initializer*/ undefined),
block);
}
return visitEachChild(node, visitor, context);
}
/**
* Visits a VariableDeclaration node with a binding pattern.
*

View File

@ -8,6 +8,7 @@
"files": [
"core.ts",
"debug.ts",
"performance.ts",
"semver.ts",

View File

@ -3154,6 +3154,7 @@ namespace ts {
*/
getExportSymbolOfSymbol(symbol: Symbol): Symbol;
getPropertySymbolOfDestructuringAssignment(location: Identifier): Symbol | undefined;
getTypeOfAssignmentPattern(pattern: AssignmentPattern): Type;
getTypeAtLocation(node: Node): Type;
getTypeFromTypeNode(node: TypeNode): Type;

View File

@ -2073,7 +2073,7 @@ namespace ts {
}
export function importFromModuleSpecifier(node: StringLiteralLike): AnyValidImportOrReExport {
return tryGetImportFromModuleSpecifier(node) || Debug.fail(Debug.showSyntaxKind(node.parent));
return tryGetImportFromModuleSpecifier(node) || Debug.failBadSyntaxKind(node.parent);
}
export function tryGetImportFromModuleSpecifier(node: StringLiteralLike): AnyValidImportOrReExport | undefined {
@ -4186,78 +4186,6 @@ namespace ts {
return getNewLine ? getNewLine() : sys ? sys.newLine : carriageReturnLineFeed;
}
/**
* Formats an enum value as a string for debugging and debug assertions.
*/
function formatEnum(value = 0, enumObject: any, isFlags?: boolean) {
const members = getEnumMembers(enumObject);
if (value === 0) {
return members.length > 0 && members[0][0] === 0 ? members[0][1] : "0";
}
if (isFlags) {
let result = "";
let remainingFlags = value;
for (let i = members.length - 1; i >= 0 && remainingFlags !== 0; i--) {
const [enumValue, enumName] = members[i];
if (enumValue !== 0 && (remainingFlags & enumValue) === enumValue) {
remainingFlags &= ~enumValue;
result = `${enumName}${result ? ", " : ""}${result}`;
}
}
if (remainingFlags === 0) {
return result;
}
}
else {
for (const [enumValue, enumName] of members) {
if (enumValue === value) {
return enumName;
}
}
}
return value.toString();
}
function getEnumMembers(enumObject: any) {
const result: [number, string][] = [];
for (const name in enumObject) {
const value = enumObject[name];
if (typeof value === "number") {
result.push([value, name]);
}
}
return stableSort<[number, string]>(result, (x, y) => compareValues(x[0], y[0]));
}
export function formatSyntaxKind(kind: SyntaxKind | undefined): string {
return formatEnum(kind, (<any>ts).SyntaxKind, /*isFlags*/ false);
}
export function formatModifierFlags(flags: ModifierFlags | undefined): string {
return formatEnum(flags, (<any>ts).ModifierFlags, /*isFlags*/ true);
}
export function formatTransformFlags(flags: TransformFlags | undefined): string {
return formatEnum(flags, (<any>ts).TransformFlags, /*isFlags*/ true);
}
export function formatEmitFlags(flags: EmitFlags | undefined): string {
return formatEnum(flags, (<any>ts).EmitFlags, /*isFlags*/ true);
}
export function formatSymbolFlags(flags: SymbolFlags | undefined): string {
return formatEnum(flags, (<any>ts).SymbolFlags, /*isFlags*/ true);
}
export function formatTypeFlags(flags: TypeFlags | undefined): string {
return formatEnum(flags, (<any>ts).TypeFlags, /*isFlags*/ true);
}
export function formatObjectFlags(flags: ObjectFlags | undefined): string {
return formatEnum(flags, (<any>ts).ObjectFlags, /*isFlags*/ true);
}
/**
* Creates a new TextRange from the provided pos and end.
*
@ -7646,6 +7574,14 @@ namespace ts {
return root + pathComponents.slice(1).join(directorySeparator);
}
export function getNormalizedAbsolutePathWithoutRoot(fileName: string, currentDirectory: string | undefined) {
return getPathWithoutRoot(getNormalizedPathComponents(fileName, currentDirectory));
}
function getPathWithoutRoot(pathComponents: ReadonlyArray<string>) {
if (pathComponents.length === 0) return "";
return pathComponents.slice(1).join(directorySeparator);
}
}
/* @internal */
@ -8420,29 +8356,6 @@ namespace ts {
return pathext ? path.slice(0, path.length - pathext.length) + (startsWith(ext, ".") ? ext : "." + ext) : path;
}
export namespace Debug {
export function showSymbol(symbol: Symbol): string {
const symbolFlags = (ts as any).SymbolFlags;
return `{ flags: ${symbolFlags ? showFlags(symbol.flags, symbolFlags) : symbol.flags}; declarations: ${map(symbol.declarations, showSyntaxKind)} }`;
}
function showFlags(flags: number, flagsEnum: { [flag: number]: string }): string {
const out: string[] = [];
for (let pow = 0; pow <= 30; pow++) {
const n = 1 << pow;
if (flags & n) {
out.push(flagsEnum[n]);
}
}
return out.join("|");
}
export function showSyntaxKind(node: Node): string {
const syntaxKind = (ts as any).SyntaxKind;
return syntaxKind ? syntaxKind[node.kind] : node.kind.toString();
}
}
export function tryParsePattern(pattern: string): Pattern | undefined {
// This should be verified outside of here and a proper error thrown.
Debug.assert(hasZeroOrOneAsteriskCharacter(pattern));

View File

@ -1558,100 +1558,4 @@ namespace ts {
function aggregateTransformFlagsForChildNodes(transformFlags: TransformFlags, nodes: NodeArray<Node>): TransformFlags {
return transformFlags | aggregateTransformFlagsForNodeArray(nodes);
}
export namespace Debug {
let isDebugInfoEnabled = false;
export function failBadSyntaxKind(node: Node, message?: string): never {
return fail(
`${message || "Unexpected node."}\r\nNode ${formatSyntaxKind(node.kind)} was unexpected.`,
failBadSyntaxKind);
}
export const assertEachNode = shouldAssert(AssertionLevel.Normal)
? (nodes: Node[], test: (node: Node) => boolean, message?: string): void => assert(
test === undefined || every(nodes, test),
message || "Unexpected node.",
() => `Node array did not pass test '${getFunctionName(test)}'.`,
assertEachNode)
: noop;
export const assertNode = shouldAssert(AssertionLevel.Normal)
? (node: Node | undefined, test: ((node: Node | undefined) => boolean) | undefined, message?: string): void => assert(
test === undefined || test(node),
message || "Unexpected node.",
() => `Node ${formatSyntaxKind(node!.kind)} did not pass test '${getFunctionName(test!)}'.`,
assertNode)
: noop;
export const assertOptionalNode = shouldAssert(AssertionLevel.Normal)
? (node: Node, test: (node: Node) => boolean, message?: string): void => assert(
test === undefined || node === undefined || test(node),
message || "Unexpected node.",
() => `Node ${formatSyntaxKind(node.kind)} did not pass test '${getFunctionName(test)}'.`,
assertOptionalNode)
: noop;
export const assertOptionalToken = shouldAssert(AssertionLevel.Normal)
? (node: Node, kind: SyntaxKind, message?: string): void => assert(
kind === undefined || node === undefined || node.kind === kind,
message || "Unexpected node.",
() => `Node ${formatSyntaxKind(node.kind)} was not a '${formatSyntaxKind(kind)}' token.`,
assertOptionalToken)
: noop;
export const assertMissingNode = shouldAssert(AssertionLevel.Normal)
? (node: Node, message?: string): void => assert(
node === undefined,
message || "Unexpected node.",
() => `Node ${formatSyntaxKind(node.kind)} was unexpected'.`,
assertMissingNode)
: noop;
/**
* Injects debug information into frequently used types.
*/
export function enableDebugInfo() {
if (isDebugInfoEnabled) return;
// Add additional properties in debug mode to assist with debugging.
Object.defineProperties(objectAllocator.getSymbolConstructor().prototype, {
__debugFlags: { get(this: Symbol) { return formatSymbolFlags(this.flags); } }
});
Object.defineProperties(objectAllocator.getTypeConstructor().prototype, {
__debugFlags: { get(this: Type) { return formatTypeFlags(this.flags); } },
__debugObjectFlags: { get(this: Type) { return this.flags & TypeFlags.Object ? formatObjectFlags((<ObjectType>this).objectFlags) : ""; } },
__debugTypeToString: { value(this: Type) { return this.checker.typeToString(this); } },
});
const nodeConstructors = [
objectAllocator.getNodeConstructor(),
objectAllocator.getIdentifierConstructor(),
objectAllocator.getTokenConstructor(),
objectAllocator.getSourceFileConstructor()
];
for (const ctor of nodeConstructors) {
if (!ctor.prototype.hasOwnProperty("__debugKind")) {
Object.defineProperties(ctor.prototype, {
__debugKind: { get(this: Node) { return formatSyntaxKind(this.kind); } },
__debugModifierFlags: { get(this: Node) { return formatModifierFlags(getModifierFlagsNoCache(this)); } },
__debugTransformFlags: { get(this: Node) { return formatTransformFlags(this.transformFlags); } },
__debugEmitFlags: { get(this: Node) { return formatEmitFlags(getEmitFlags(this)); } },
__debugGetText: {
value(this: Node, includeTrivia?: boolean) {
if (nodeIsSynthesized(this)) return "";
const parseNode = getParseTreeNode(this);
const sourceFile = parseNode && getSourceFileOfNode(parseNode);
return sourceFile ? getSourceTextOfNodeFromSourceFile(sourceFile, parseNode, includeTrivia) : "";
}
}
});
}
}
isDebugInfoEnabled = true;
}
}
}

View File

@ -798,8 +798,8 @@ namespace FourSlash {
}
private verifyCompletionEntry(actual: ts.CompletionEntry, expected: FourSlashInterface.ExpectedCompletionEntry) {
const { insertText, replacementSpan, hasAction, isRecommended, kind, kindModifiers, text, documentation, tags, source, sourceDisplay } = typeof expected === "string"
? { insertText: undefined, replacementSpan: undefined, hasAction: undefined, isRecommended: undefined, kind: undefined, kindModifiers: undefined, text: undefined, documentation: undefined, tags: undefined, source: undefined, sourceDisplay: undefined }
const { insertText, replacementSpan, hasAction, isRecommended, kind, kindModifiers, text, documentation, tags, source, sourceDisplay, sortText } = typeof expected === "string"
? { insertText: undefined, replacementSpan: undefined, hasAction: undefined, isRecommended: undefined, kind: undefined, kindModifiers: undefined, text: undefined, documentation: undefined, tags: undefined, source: undefined, sourceDisplay: undefined, sortText: undefined }
: expected;
if (actual.insertText !== insertText) {
@ -825,6 +825,7 @@ namespace FourSlash {
assert.equal(actual.hasAction, hasAction);
assert.equal(actual.isRecommended, isRecommended);
assert.equal(actual.source, source);
assert.equal(actual.sortText, sortText || ts.Completions.SortText.LocationPriority, this.messageAtLastKnownMarker(`Actual entry: ${JSON.stringify(actual)}`));
if (text !== undefined) {
const actualDetails = this.getCompletionEntryDetails(actual.name, actual.source)!;
@ -1207,7 +1208,7 @@ Actual: ${stringify(fullActual)}`);
}
}
public verifySignatureHelpPresence(expectPresent: boolean, triggerReason: ts.SignatureHelpTriggerReason | undefined, markers: ReadonlyArray<string>) {
public verifySignatureHelpPresence(expectPresent: boolean, triggerReason: ts.SignatureHelpTriggerReason | undefined, markers: ReadonlyArray<string | Marker>) {
if (markers.length) {
for (const marker of markers) {
this.goToMarker(marker);
@ -1503,7 +1504,7 @@ Actual: ${stringify(fullActual)}`);
}
public baselineSmartSelection() {
const n = ts.sys.newLine;
const n = "\n";
const baselineFile = this.getBaselineFileName();
const markers = this.getMarkers();
const fileContent = this.activeFile.content;
@ -3767,15 +3768,15 @@ namespace FourSlashInterface {
assert(ranges.length !== 0, "Array of ranges is expected to be non-empty");
}
public noSignatureHelp(...markers: string[]): void {
public noSignatureHelp(...markers: (string | FourSlash.Marker)[]): void {
this.state.verifySignatureHelpPresence(/*expectPresent*/ false, /*triggerReason*/ undefined, markers);
}
public noSignatureHelpForTriggerReason(reason: ts.SignatureHelpTriggerReason, ...markers: string[]): void {
public noSignatureHelpForTriggerReason(reason: ts.SignatureHelpTriggerReason, ...markers: (string | FourSlash.Marker)[]): void {
this.state.verifySignatureHelpPresence(/*expectPresent*/ false, reason, markers);
}
public signatureHelpPresentForTriggerReason(reason: ts.SignatureHelpTriggerReason, ...markers: string[]): void {
public signatureHelpPresentForTriggerReason(reason: ts.SignatureHelpTriggerReason, ...markers: (string | FourSlash.Marker)[]): void {
this.state.verifySignatureHelpPresence(/*expectPresent*/ true, reason, markers);
}
@ -4434,18 +4435,63 @@ namespace FourSlashInterface {
}
}
export namespace Completion {
const functionEntry = (name: string): ExpectedCompletionEntryObject => ({ name, kind: "function", kindModifiers: "declare" });
const varEntry = (name: string): ExpectedCompletionEntryObject => ({ name, kind: "var", kindModifiers: "declare" });
const moduleEntry = (name: string): ExpectedCompletionEntryObject => ({ name, kind: "module", kindModifiers: "declare" });
const keywordEntry = (name: string): ExpectedCompletionEntryObject => ({ name, kind: "keyword" });
const methodEntry = (name: string): ExpectedCompletionEntryObject => ({ name, kind: "method", kindModifiers: "declare" });
const propertyEntry = (name: string): ExpectedCompletionEntryObject => ({ name, kind: "property", kindModifiers: "declare" });
const interfaceEntry = (name: string): ExpectedCompletionEntryObject => ({ name, kind: "interface", kindModifiers: "declare" });
const typeEntry = (name: string): ExpectedCompletionEntryObject => ({ name, kind: "type", kindModifiers: "declare" });
export import SortText = ts.Completions.SortText;
const functionEntry = (name: string): ExpectedCompletionEntryObject => ({
name,
kind: "function",
kindModifiers: "declare",
sortText: SortText.GlobalsOrKeywords
});
const varEntry = (name: string): ExpectedCompletionEntryObject => ({
name,
kind: "var",
kindModifiers: "declare",
sortText: SortText.GlobalsOrKeywords
});
const moduleEntry = (name: string): ExpectedCompletionEntryObject => ({
name,
kind: "module",
kindModifiers: "declare",
sortText: SortText.GlobalsOrKeywords
});
const keywordEntry = (name: string): ExpectedCompletionEntryObject => ({
name,
kind: "keyword",
sortText: SortText.GlobalsOrKeywords
});
const methodEntry = (name: string): ExpectedCompletionEntryObject => ({
name,
kind: "method",
kindModifiers: "declare",
sortText: SortText.LocationPriority
});
const propertyEntry = (name: string): ExpectedCompletionEntryObject => ({
name,
kind: "property",
kindModifiers: "declare",
sortText: SortText.LocationPriority
});
const interfaceEntry = (name: string): ExpectedCompletionEntryObject => ({
name,
kind: "interface",
kindModifiers: "declare",
sortText: SortText.GlobalsOrKeywords
});
const typeEntry = (name: string): ExpectedCompletionEntryObject => ({
name,
kind: "type",
kindModifiers: "declare",
sortText: SortText.GlobalsOrKeywords
});
const res: ExpectedCompletionEntryObject[] = [];
for (let i = ts.SyntaxKind.FirstKeyword; i <= ts.SyntaxKind.LastKeyword; i++) {
res.push({ name: ts.Debug.assertDefined(ts.tokenToString(i)), kind: "keyword" });
res.push({
name: ts.Debug.assertDefined(ts.tokenToString(i)),
kind: "keyword",
sortText: SortText.GlobalsOrKeywords
});
}
export const keywordsWithUndefined: ReadonlyArray<ExpectedCompletionEntryObject> = res;
export const keywords: ReadonlyArray<ExpectedCompletionEntryObject> = keywordsWithUndefined.filter(k => k.name !== "undefined");
@ -4552,11 +4598,15 @@ namespace FourSlashInterface {
moduleEntry("Intl"),
];
export const globalThisEntry: ExpectedCompletionEntry = {
name: "globalThis",
kind: "module",
sortText: SortText.GlobalsOrKeywords
};
export const globalTypes = globalTypesPlus([]);
export function globalTypesPlus(plus: ReadonlyArray<ExpectedCompletionEntry>): ReadonlyArray<ExpectedCompletionEntry> {
return [
{ name: "globalThis", kind: "module" },
globalThisEntry,
...globalTypeDecls,
...plus,
...typeKeywords,
@ -4605,7 +4655,11 @@ namespace FourSlashInterface {
export const classElementInJsKeywords = getInJsKeywords(classElementKeywords);
export const constructorParameterKeywords: ReadonlyArray<ExpectedCompletionEntryObject> =
["private", "protected", "public", "readonly"].map((name): ExpectedCompletionEntryObject => ({ name, kind: "keyword" }));
["private", "protected", "public", "readonly"].map((name): ExpectedCompletionEntryObject => ({
name,
kind: "keyword",
sortText: SortText.GlobalsOrKeywords
}));
export const functionMembers: ReadonlyArray<ExpectedCompletionEntryObject> = [
methodEntry("apply"),
@ -4834,13 +4888,18 @@ namespace FourSlashInterface {
"await",
].map(keywordEntry);
export const undefinedVarEntry: ExpectedCompletionEntry = {
name: "undefined",
kind: "var",
sortText: SortText.GlobalsOrKeywords
};
// TODO: many of these are inappropriate to always provide
export const globalsInsideFunction = (plus: ReadonlyArray<ExpectedCompletionEntry>): ReadonlyArray<ExpectedCompletionEntry> => [
{ name: "arguments", kind: "local var" },
...plus,
{ name: "globalThis", kind: "module" },
globalThisEntry,
...globalsVars,
{ name: "undefined", kind: "var" },
undefinedVarEntry,
...globalKeywordsInsideFunction,
];
@ -4849,10 +4908,10 @@ namespace FourSlashInterface {
// TODO: many of these are inappropriate to always provide
export const globalsInJsInsideFunction = (plus: ReadonlyArray<ExpectedCompletionEntry>): ReadonlyArray<ExpectedCompletionEntry> => [
{ name: "arguments", kind: "local var" },
{ name: "globalThis", kind: "module" },
globalThisEntry,
...globalsVars,
...plus,
{ name: "undefined", kind: "var" },
undefinedVarEntry,
...globalInJsKeywordsInsideFunction,
];
@ -4990,34 +5049,34 @@ namespace FourSlashInterface {
})();
export const globals: ReadonlyArray<ExpectedCompletionEntryObject> = [
{ name: "globalThis", kind: "module" },
globalThisEntry,
...globalsVars,
{ name: "undefined", kind: "var" },
undefinedVarEntry,
...globalKeywords
];
export const globalsInJs: ReadonlyArray<ExpectedCompletionEntryObject> = [
{ name: "globalThis", kind: "module" },
globalThisEntry,
...globalsVars,
{ name: "undefined", kind: "var" },
undefinedVarEntry,
...globalInJsKeywords
];
export function globalsPlus(plus: ReadonlyArray<ExpectedCompletionEntry>): ReadonlyArray<ExpectedCompletionEntry> {
return [
{ name: "globalThis", kind: "module" },
globalThisEntry,
...globalsVars,
...plus,
{ name: "undefined", kind: "var" },
undefinedVarEntry,
...globalKeywords];
}
export function globalsInJsPlus(plus: ReadonlyArray<ExpectedCompletionEntry>): ReadonlyArray<ExpectedCompletionEntry> {
return [
{ name: "globalThis", kind: "module" },
globalThisEntry,
...globalsVars,
...plus,
{ name: "undefined", kind: "var" },
undefinedVarEntry,
...globalInJsKeywords];
}
}
@ -5050,6 +5109,7 @@ namespace FourSlashInterface {
readonly documentation?: string;
readonly sourceDisplay?: string;
readonly tags?: ReadonlyArray<ts.JSDocTagInfo>;
readonly sortText?: ts.Completions.SortText;
}
export interface VerifyCompletionsOptions {
@ -5064,7 +5124,7 @@ namespace FourSlashInterface {
}
export interface VerifySignatureHelpOptions {
readonly marker?: ArrayOrSingle<string>;
readonly marker?: ArrayOrSingle<string | FourSlash.Marker>;
/** @default 1 */
readonly overloadsCount?: number;
/** @default undefined */

View File

@ -17328,7 +17328,8 @@ interface WorkerEventMap extends AbstractWorkerEventMap {
/** An interface of the Web Workers API represents a background task that can be easily created and can send messages back to its creator. Creating a worker is as simple as calling the Worker() constructor and specifying a script to be run in the worker thread. */
interface Worker extends EventTarget, AbstractWorker {
onmessage: ((this: Worker, ev: MessageEvent) => any) | null;
postMessage(message: any, transfer?: Transferable[]): void;
postMessage(message: any, transfer: Transferable[]): void;
postMessage(message: any, options?: PostMessageOptions): void;
terminate(): void;
addEventListener<K extends keyof WorkerEventMap>(type: K, listener: (this: Worker, ev: WorkerEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;

2
src/lib/es5.d.ts vendored
View File

@ -513,7 +513,7 @@ interface Boolean {
interface BooleanConstructor {
new(value?: any): Boolean;
<T>(value?: T): value is Exclude<T, false | null | undefined | '' | 0>;
<T>(value?: T): boolean;
readonly prototype: Boolean;
}

View File

@ -4231,7 +4231,8 @@ interface WorkerEventMap extends AbstractWorkerEventMap {
/** An interface of the Web Workers API represents a background task that can be easily created and can send messages back to its creator. Creating a worker is as simple as calling the Worker() constructor and specifying a script to be run in the worker thread. */
interface Worker extends EventTarget, AbstractWorker {
onmessage: ((this: Worker, ev: MessageEvent) => any) | null;
postMessage(message: any, transfer?: Transferable[]): void;
postMessage(message: any, transfer: Transferable[]): void;
postMessage(message: any, options?: PostMessageOptions): void;
terminate(): void;
addEventListener<K extends keyof WorkerEventMap>(type: K, listener: (this: Worker, ev: WorkerEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;

View File

@ -198,13 +198,13 @@ namespace ts.server {
return hasOneOrMoreJsAndNoTsFiles(this);
}
public static resolveModule(moduleName: string, initialDir: string, host: ServerHost, log: (message: string) => void): {} | undefined {
public static resolveModule(moduleName: string, initialDir: string, host: ServerHost, log: (message: string) => void, logErrors?: (message: string) => void): {} | undefined {
const resolvedPath = normalizeSlashes(host.resolvePath(combinePaths(initialDir, "node_modules")));
log(`Loading ${moduleName} from ${initialDir} (resolved to ${resolvedPath})`);
const result = host.require!(resolvedPath, moduleName); // TODO: GH#18217
if (result.error) {
const err = result.error.stack || result.error.message || JSON.stringify(result.error);
log(`Failed to load module '${moduleName}': ${err}`);
(logErrors || log)(`Failed to load module '${moduleName}' from ${resolvedPath}: ${err}`);
return undefined;
}
return result.module;
@ -1142,12 +1142,11 @@ namespace ts.server {
protected enablePlugin(pluginConfigEntry: PluginImport, searchPaths: string[], pluginConfigOverrides: Map<any> | undefined) {
this.projectService.logger.info(`Enabling plugin ${pluginConfigEntry.name} from candidate paths: ${searchPaths.join(",")}`);
const log = (message: string) => {
this.projectService.logger.info(message);
};
const log = (message: string) => this.projectService.logger.info(message);
let errorLogs: string[] | undefined;
const logError = (message: string) => { (errorLogs || (errorLogs = [])).push(message); };
const resolvedModule = firstDefined(searchPaths, searchPath =>
<PluginModuleFactory | undefined>Project.resolveModule(pluginConfigEntry.name, searchPath, this.projectService.host, log));
<PluginModuleFactory | undefined>Project.resolveModule(pluginConfigEntry.name, searchPath, this.projectService.host, log, logError));
if (resolvedModule) {
const configurationOverride = pluginConfigOverrides && pluginConfigOverrides.get(pluginConfigEntry.name);
if (configurationOverride) {
@ -1160,6 +1159,7 @@ namespace ts.server {
this.enableProxy(resolvedModule, pluginConfigEntry);
}
else {
forEach(errorLogs, log);
this.projectService.logger.info(`Couldn't find ${pluginConfigEntry.name}`);
}
}

View File

@ -15,11 +15,11 @@ namespace ts.codefix {
function makeChange(changeTracker: textChanges.ChangeTracker, sourceFile: SourceFile, pos: number) {
const token = getTokenAtPosition(sourceFile, pos);
if (!isIdentifier(token)) {
return Debug.fail("add-name-to-nameless-parameter operates on identifiers, but got a " + formatSyntaxKind(token.kind));
return Debug.fail("add-name-to-nameless-parameter operates on identifiers, but got a " + Debug.formatSyntaxKind(token.kind));
}
const param = token.parent;
if (!isParameter(param)) {
return Debug.fail("Tried to add a parameter name to a non-parameter: " + formatSyntaxKind(token.kind));
return Debug.fail("Tried to add a parameter name to a non-parameter: " + Debug.formatSyntaxKind(token.kind));
}
const i = param.parent.parameters.indexOf(param);
Debug.assert(!param.type, "Tried to add a parameter name to a parameter that already had one.");

View File

@ -1,5 +1,12 @@
/* @internal */
namespace ts.Completions {
export enum SortText {
LocationPriority = "0",
SuggestedClassMembers = "1",
GlobalsOrKeywords = "2",
AutoImportSuggestions = "3",
JavascriptIdentifiers = "4"
}
export type Log = (message: string) => void;
const enum SymbolOriginInfoKind { ThisType, SymbolMemberNoExport, SymbolMemberExport, Export }
@ -22,6 +29,8 @@ namespace ts.Completions {
*/
type SymbolOriginInfoMap = (SymbolOriginInfo | undefined)[];
type SymbolSortTextMap = (SortText | undefined)[];
const enum KeywordCompletionFilters {
None, // No keywords
All, // Every possible keyword (TODO: This is never appropriate)
@ -40,7 +49,9 @@ namespace ts.Completions {
const compilerOptions = program.getCompilerOptions();
const contextToken = findPrecedingToken(position, sourceFile);
if (triggerCharacter && !isValidTrigger(sourceFile, triggerCharacter, contextToken, position)) return undefined;
if (triggerCharacter && !isInString(sourceFile, position, contextToken) && !isValidTrigger(sourceFile, triggerCharacter, contextToken, position)) {
return undefined;
}
const stringCompletions = StringCompletions.getStringLiteralCompletions(sourceFile, position, contextToken, typeChecker, compilerOptions, host, log, preferences);
if (stringCompletions) {
@ -78,7 +89,21 @@ namespace ts.Completions {
}
function completionInfoFromData(sourceFile: SourceFile, typeChecker: TypeChecker, compilerOptions: CompilerOptions, log: Log, completionData: CompletionData, preferences: UserPreferences): CompletionInfo | undefined {
const { symbols, completionKind, isInSnippetScope, isNewIdentifierLocation, location, propertyAccessToConvert, keywordFilters, literals, symbolToOriginInfoMap, recommendedCompletion, isJsxInitializer, insideJsDocTagTypeExpression } = completionData;
const {
symbols,
completionKind,
isInSnippetScope,
isNewIdentifierLocation,
location,
propertyAccessToConvert,
keywordFilters,
literals,
symbolToOriginInfoMap,
recommendedCompletion,
isJsxInitializer,
insideJsDocTagTypeExpression,
symbolToSortTextMap,
} = completionData;
if (location && location.parent && isJsxClosingElement(location.parent)) {
// In the TypeScript JSX element, if such element is not defined. When users query for completion at closing tag,
@ -93,7 +118,7 @@ namespace ts.Completions {
name: tagName.getFullText(sourceFile) + (hasClosingAngleBracket ? "" : ">"),
kind: ScriptElementKind.classElement,
kindModifiers: undefined,
sortText: "0",
sortText: SortText.LocationPriority,
};
return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: false, entries: [entry] };
}
@ -101,7 +126,22 @@ namespace ts.Completions {
const entries: CompletionEntry[] = [];
if (isUncheckedFile(sourceFile, compilerOptions)) {
const uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target!, log, completionKind, preferences, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap);
const uniqueNames = getCompletionEntriesFromSymbols(
symbols,
entries,
location,
sourceFile,
typeChecker,
compilerOptions.target!,
log,
completionKind,
preferences,
propertyAccessToConvert,
isJsxInitializer,
recommendedCompletion,
symbolToOriginInfoMap,
symbolToSortTextMap
);
getJSCompletionEntries(sourceFile, location!.pos, uniqueNames, compilerOptions.target!, entries); // TODO: GH#18217
}
else {
@ -109,7 +149,22 @@ namespace ts.Completions {
return undefined;
}
getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target!, log, completionKind, preferences, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap);
getCompletionEntriesFromSymbols(
symbols,
entries,
location,
sourceFile,
typeChecker,
compilerOptions.target!,
log,
completionKind,
preferences,
propertyAccessToConvert,
isJsxInitializer,
recommendedCompletion,
symbolToOriginInfoMap,
symbolToSortTextMap
);
}
if (keywordFilters !== KeywordCompletionFilters.None) {
@ -160,7 +215,7 @@ namespace ts.Completions {
name: realName,
kind: ScriptElementKind.warning,
kindModifiers: "",
sortText: "1"
sortText: SortText.JavascriptIdentifiers
});
}
});
@ -169,28 +224,23 @@ namespace ts.Completions {
const completionNameForLiteral = (literal: string | number | PseudoBigInt) =>
typeof literal === "object" ? pseudoBigIntToString(literal) + "n" : JSON.stringify(literal);
function createCompletionEntryForLiteral(literal: string | number | PseudoBigInt): CompletionEntry {
return { name: completionNameForLiteral(literal), kind: ScriptElementKind.string, kindModifiers: ScriptElementKindModifier.none, sortText: "0" };
return { name: completionNameForLiteral(literal), kind: ScriptElementKind.string, kindModifiers: ScriptElementKindModifier.none, sortText: SortText.LocationPriority };
}
function createCompletionEntry(
symbol: Symbol,
sortText: SortText,
location: Node | undefined,
sourceFile: SourceFile,
typeChecker: TypeChecker,
target: ScriptTarget,
kind: CompletionKind,
name: string,
needsConvertPropertyAccess: boolean,
origin: SymbolOriginInfo | undefined,
recommendedCompletion: Symbol | undefined,
propertyAccessToConvert: PropertyAccessExpression | undefined,
isJsxInitializer: IsJsxInitializer | undefined,
preferences: UserPreferences,
): CompletionEntry | undefined {
const info = getCompletionEntryDisplayNameForSymbol(symbol, target, origin, kind);
if (!info) {
return undefined;
}
const { name, needsConvertPropertyAccess } = info;
let insertText: string | undefined;
let replacementSpan: TextSpan | undefined;
if (origin && origin.kind === SymbolOriginInfoKind.ThisType) {
@ -230,7 +280,7 @@ namespace ts.Completions {
name,
kind: SymbolDisplay.getSymbolKind(typeChecker, symbol, location!), // TODO: GH#18217
kindModifiers: SymbolDisplay.getSymbolModifiers(symbol),
sortText: "0",
sortText,
source: getSourceFromOrigin(origin),
hasAction: trueOrUndefined(!!origin && originIsExport(origin)),
isRecommended: trueOrUndefined(isRecommendedCompletionMatch(symbol, recommendedCompletion, typeChecker)),
@ -266,6 +316,7 @@ namespace ts.Completions {
isJsxInitializer?: IsJsxInitializer,
recommendedCompletion?: Symbol,
symbolToOriginInfoMap?: SymbolOriginInfoMap,
symbolToSortTextMap?: SymbolSortTextMap,
): Map<true> {
const start = timestamp();
// Tracks unique names.
@ -275,13 +326,30 @@ namespace ts.Completions {
const uniques = createMap<true>();
for (const symbol of symbols) {
const origin = symbolToOriginInfoMap ? symbolToOriginInfoMap[getSymbolId(symbol)] : undefined;
const entry = createCompletionEntry(symbol, location, sourceFile, typeChecker, target, kind, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, preferences);
if (!entry) {
const info = getCompletionEntryDisplayNameForSymbol(symbol, target, origin, kind);
if (!info) {
continue;
}
const { name, needsConvertPropertyAccess } = info;
if (uniques.has(name)) {
continue;
}
const { name } = entry;
if (uniques.has(name)) {
const entry = createCompletionEntry(
symbol,
symbolToSortTextMap && symbolToSortTextMap[getSymbolId(symbol)] || SortText.LocationPriority,
location,
sourceFile,
typeChecker,
name,
needsConvertPropertyAccess,
origin,
recommendedCompletion,
propertyAccessToConvert,
isJsxInitializer,
preferences
);
if (!entry) {
continue;
}
@ -321,7 +389,7 @@ namespace ts.Completions {
name,
kindModifiers: ScriptElementKindModifier.none,
kind: ScriptElementKind.label,
sortText: "0"
sortText: SortText.LocationPriority
});
}
}
@ -358,7 +426,7 @@ namespace ts.Completions {
// We don't need to perform character checks here because we're only comparing the
// name against 'entryName' (which is known to be good), not building a new
// completion entry.
return firstDefined<Symbol, SymbolCompletion>(symbols, (symbol): SymbolCompletion | undefined => { // TODO: Shouldn't need return type annotation (GH#12632)
return firstDefined(symbols, (symbol): SymbolCompletion | undefined => {
const origin = symbolToOriginInfoMap[getSymbolId(symbol)];
const info = getCompletionEntryDisplayNameForSymbol(symbol, compilerOptions.target!, origin, completionKind);
return info && info.name === entryId.name && getSourceFromOrigin(origin) === entryId.source
@ -512,6 +580,7 @@ namespace ts.Completions {
readonly previousToken: Node | undefined;
readonly isJsxInitializer: IsJsxInitializer;
readonly insideJsDocTagTypeExpression: boolean;
readonly symbolToSortTextMap: SymbolSortTextMap;
}
type Request = { readonly kind: CompletionDataKind.JsDocTagName | CompletionDataKind.JsDocTag } | { readonly kind: CompletionDataKind.JsDocParameterName, tag: JSDocParameterTag };
@ -804,6 +873,7 @@ namespace ts.Completions {
let keywordFilters = KeywordCompletionFilters.None;
let symbols: Symbol[] = [];
const symbolToOriginInfoMap: SymbolOriginInfoMap = [];
const symbolToSortTextMap: SymbolSortTextMap = [];
if (isRightOfDot) {
getTypeScriptMemberSymbols();
@ -853,7 +923,8 @@ namespace ts.Completions {
recommendedCompletion,
previousToken,
isJsxInitializer,
insideJsDocTagTypeExpression
insideJsDocTagTypeExpression,
symbolToSortTextMap
};
type JSDocTagWithTypeExpression = JSDocParameterTag | JSDocPropertyTag | JSDocReturnTag | JSDocTypeTag | JSDocTypedefTag;
@ -1054,6 +1125,12 @@ namespace ts.Completions {
const symbolMeanings = (isTypeOnly ? SymbolFlags.None : SymbolFlags.Value) | SymbolFlags.Type | SymbolFlags.Namespace | SymbolFlags.Alias;
symbols = Debug.assertEachDefined(typeChecker.getSymbolsInScope(scopeNode, symbolMeanings), "getSymbolsInScope() should all be defined");
for (const symbol of symbols) {
if (!typeChecker.isArgumentsSymbol(symbol) &&
!some(symbol.declarations, d => d.getSourceFile() === sourceFile)) {
symbolToSortTextMap[getSymbolId(symbol)] = SortText.GlobalsOrKeywords;
}
}
// Need to insert 'this.' before properties of `this` type, so only do that if `includeInsertTextCompletions`
if (preferences.includeCompletionsWithInsertText && scopeNode.kind !== SyntaxKind.SourceFile) {
@ -1062,6 +1139,7 @@ namespace ts.Completions {
for (const symbol of getPropertiesForCompletion(thisType, typeChecker)) {
symbolToOriginInfoMap[getSymbolId(symbol)] = { kind: SymbolOriginInfoKind.ThisType };
symbols.push(symbol);
symbolToSortTextMap[getSymbolId(symbol)] = SortText.SuggestedClassMembers;
}
}
}
@ -1195,6 +1273,7 @@ namespace ts.Completions {
// So in `declare namespace foo {} declare module "foo" { export = foo; }`, there will just be the global completion for `foo`.
some(resolvedModuleSymbol.declarations, d => !!d.getSourceFile().externalModuleIndicator)) {
symbols.push(resolvedModuleSymbol);
symbolToSortTextMap[getSymbolId(resolvedModuleSymbol)] = SortText.AutoImportSuggestions;
symbolToOriginInfoMap[getSymbolId(resolvedModuleSymbol)] = { kind: SymbolOriginInfoKind.Export, moduleSymbol, isDefaultExport: false };
}
@ -1220,6 +1299,7 @@ namespace ts.Completions {
const origin: SymbolOriginInfoExport = { kind: SymbolOriginInfoKind.Export, moduleSymbol, isDefaultExport };
if (detailsEntryId || stringContainsCharactersInOrder(getSymbolName(symbol, origin, target).toLowerCase(), tokenTextLowerCase)) {
symbols.push(symbol);
symbolToSortTextMap[getSymbolId(symbol)] = SortText.AutoImportSuggestions;
symbolToOriginInfoMap[getSymbolId(symbol)] = origin;
}
}
@ -1941,7 +2021,7 @@ namespace ts.Completions {
name: tokenToString(i)!,
kind: ScriptElementKind.keyword,
kindModifiers: ScriptElementKindModifier.none,
sortText: "0"
sortText: SortText.GlobalsOrKeywords
});
}
return res;

View File

@ -635,7 +635,7 @@ namespace ts.FindAllReferences.Core {
// Ignore UMD module and global merge
if (symbol.flags & SymbolFlags.Transient) return undefined;
// Assertions for GH#21814. We should be handling SourceFile symbols in `getReferencedSymbolsForModule` instead of getting here.
Debug.fail(`Unexpected symbol at ${Debug.showSyntaxKind(node)}: ${Debug.showSymbol(symbol)}`);
Debug.fail(`Unexpected symbol at ${Debug.formatSyntaxKind(node.kind)}: ${Debug.formatSymbol(symbol)}`);
}
return isTypeLiteralNode(decl.parent) && isUnionTypeNode(decl.parent.parent)
? checker.getPropertyOfType(checker.getTypeFromTypeNode(decl.parent.parent), symbol.name)

View File

@ -133,7 +133,7 @@ namespace ts.FindAllReferences {
break;
default:
Debug.assertNever(direct, `Unexpected import kind: ${Debug.showSyntaxKind(direct)}`);
Debug.failBadSyntaxKind(direct, "Unexpected import kind.");
}
}
}
@ -515,7 +515,7 @@ namespace ts.FindAllReferences {
const sym = useLhsSymbol ? checker.getSymbolAtLocation(cast(node.left, isPropertyAccessExpression).name) : symbol;
// Better detection for GH#20803
if (sym && !(checker.getMergedSymbol(sym.parent!).flags & SymbolFlags.Module)) {
Debug.fail(`Special property assignment kind does not have a module as its parent. Assignment is ${Debug.showSymbol(sym)}, parent is ${Debug.showSymbol(sym.parent!)}`);
Debug.fail(`Special property assignment kind does not have a module as its parent. Assignment is ${Debug.formatSymbol(sym)}, parent is ${Debug.formatSymbol(sym.parent!)}`);
}
return sym && exportInfo(sym, kind);
}

View File

@ -173,7 +173,7 @@ namespace ts {
const textPos = scanner.getTextPos();
if (textPos <= end) {
if (token === SyntaxKind.Identifier) {
Debug.fail(`Did not expect ${Debug.showSyntaxKind(parent)} to have an Identifier in its trivia`);
Debug.fail(`Did not expect ${Debug.formatSyntaxKind(parent.kind)} to have an Identifier in its trivia`);
}
nodes.push(createNode(token, pos, textPos, parent));
}

View File

@ -133,11 +133,21 @@ namespace ts.SignatureHelp {
}
function containsPrecedingToken(startingToken: Node, sourceFile: SourceFile, container: Node) {
const precedingToken = Debug.assertDefined(
findPrecedingToken(startingToken.getFullStart(), sourceFile, startingToken.parent, /*excludeJsdoc*/ true)
);
return rangeContainsRange(container, precedingToken);
const pos = startingToken.getFullStart();
// Theres a possibility that `startingToken.parent` contains only `startingToken` and
// missing nodes, none of which are valid to be returned by `findPrecedingToken`. In that
// case, the preceding token we want is actually higher up the tree—almost definitely the
// next parent, but theoretically the situation with missing nodes might be happening on
// multiple nested levels.
let currentParent: Node | undefined = startingToken.parent;
while (currentParent) {
const precedingToken = findPrecedingToken(pos, sourceFile, currentParent, /*excludeJsdoc*/ true);
if (precedingToken) {
return rangeContainsRange(container, precedingToken);
}
currentParent = currentParent.parent;
}
return Debug.fail("Could not find preceding token");
}
export interface ArgumentInfoForCompletions {
@ -455,7 +465,7 @@ namespace ts.SignatureHelp {
for (let n = node; !isSourceFile(n) && (isManuallyInvoked || !isBlock(n)); n = n.parent) {
// If the node is not a subspan of its parent, this is a big problem.
// There have been crashes that might be caused by this violation.
Debug.assert(rangeContainsRange(n.parent, n), "Not a subspan", () => `Child: ${Debug.showSyntaxKind(n)}, parent: ${Debug.showSyntaxKind(n.parent)}`);
Debug.assert(rangeContainsRange(n.parent, n), "Not a subspan", () => `Child: ${Debug.formatSyntaxKind(n.kind)}, parent: ${Debug.formatSyntaxKind(n.parent.kind)}`);
const argumentInfo = getImmediatelyContainingArgumentOrContextualParameterInfo(n, position, sourceFile, checker);
if (argumentInfo) {
return argumentInfo;

View File

@ -21,7 +21,17 @@ namespace ts.Completions.StringCompletions {
return convertPathCompletions(completion.paths);
case StringLiteralCompletionKind.Properties: {
const entries: CompletionEntry[] = [];
getCompletionEntriesFromSymbols(completion.symbols, entries, sourceFile, sourceFile, checker, ScriptTarget.ESNext, log, CompletionKind.String, preferences); // Target will not be used, so arbitrary
getCompletionEntriesFromSymbols(
completion.symbols,
entries,
sourceFile,
sourceFile,
checker,
ScriptTarget.ESNext,
log,
CompletionKind.String,
preferences
); // Target will not be used, so arbitrary
return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: completion.hasIndexSignature, entries };
}
case StringLiteralCompletionKind.Types: {
@ -60,7 +70,7 @@ namespace ts.Completions.StringCompletions {
const isGlobalCompletion = false; // We don't want the editor to offer any other completions, such as snippets, inside a comment.
const isNewIdentifierLocation = true; // The user may type in a path that doesn't yet exist, creating a "new identifier" with respect to the collection of identifiers the server is aware of.
const entries = pathCompletions.map(({ name, kind, span, extension }): CompletionEntry =>
({ name, kind, kindModifiers: kindModifiersFromExtension(extension), sortText: "0", replacementSpan: span }));
({ name, kind, kindModifiers: kindModifiersFromExtension(extension), sortText: SortText.LocationPriority, replacementSpan: span }));
return { isGlobalCompletion, isMemberCompletion: false, isNewIdentifierLocation, entries };
}
function kindModifiersFromExtension(extension: Extension | undefined): ScriptElementKindModifier {

View File

@ -197,13 +197,13 @@ namespace ts {
const caseSensitiveBasePath = "/dev/";
const caseSensitiveHost = new fakes.ParseConfigHost(createFileSystem(/*ignoreCase*/ false, caseSensitiveBasePath, "/"));
function verifyDiagnostics(actual: Diagnostic[], expected: {code: number, category: DiagnosticCategory, messageText: string}[]) {
function verifyDiagnostics(actual: Diagnostic[], expected: { code: number; messageText: string; }[]) {
assert.isTrue(expected.length === actual.length, `Expected error: ${JSON.stringify(expected)}. Actual error: ${JSON.stringify(actual)}.`);
for (let i = 0; i < actual.length; i++) {
const actualError = actual[i];
const expectedError = expected[i];
assert.equal(actualError.code, expectedError.code, "Error code mismatch");
assert.equal(actualError.category, expectedError.category, "Category mismatch");
assert.equal(actualError.category, DiagnosticCategory.Error, "Category mismatch"); // Should always be error
assert.equal(flattenDiagnosticMessageText(actualError.messageText, "\n"), expectedError.messageText);
}
}
@ -246,7 +246,7 @@ namespace ts {
});
}
function testFailure(name: string, entry: string, expectedDiagnostics: { code: number, category: DiagnosticCategory, messageText: string }[]) {
function testFailure(name: string, entry: string, expectedDiagnostics: { code: number; messageText: string; }[]) {
it(name, () => {
const parsed = getParseCommandLine(entry);
verifyDiagnostics(parsed.errors, expectedDiagnostics);
@ -280,26 +280,22 @@ namespace ts {
testFailure("can report errors on circular imports", "circular.json", [
{
code: 18000,
category: DiagnosticCategory.Error,
messageText: `Circularity detected while resolving configuration: ${[combinePaths(basePath, "circular.json"), combinePaths(basePath, "circular2.json"), combinePaths(basePath, "circular.json")].join(" -> ")}`
}
]);
testFailure("can report missing configurations", "missing.json", [{
code: 6096,
category: DiagnosticCategory.Message,
messageText: `File './missing2' does not exist.`
code: 6053,
messageText: `File './missing2' not found.`
}]);
testFailure("can report errors in extended configs", "failure.json", [{
code: 6114,
category: DiagnosticCategory.Error,
messageText: `Unknown option 'excludes'. Did you mean 'exclude'?`
}]);
testFailure("can error when 'extends' is not a string", "extends.json", [{
code: 5024,
category: DiagnosticCategory.Error,
messageText: `Compiler option 'extends' requires a value of type string.`
}]);

View File

@ -1,7 +1,7 @@
namespace ts {
describe("unittests:: FactoryAPI", () => {
function assertSyntaxKind(node: Node, expected: SyntaxKind) {
assert.strictEqual(node.kind, expected, `Actual: ${Debug.showSyntaxKind(node)} Expected: ${(ts as any).SyntaxKind[expected]}`);
assert.strictEqual(node.kind, expected, `Actual: ${Debug.formatSyntaxKind(node.kind)} Expected: ${Debug.formatSyntaxKind(expected)}`);
}
describe("createExportAssignment", () => {
it("parenthesizes default export if necessary", () => {

View File

@ -530,7 +530,7 @@ export = C;
});
});
describe("unittests:: moduleResolution:: Files with different casing", () => {
describe("unittests:: moduleResolution:: Files with different casing with forceConsistentCasingInFileNames", () => {
let library: SourceFile;
function test(files: Map<string>, options: CompilerOptions, currentDirectory: string, useCaseSensitiveFileNames: boolean, rootFiles: string[], diagnosticCodes: number[]): void {
const getCanonicalFileName = createGetCanonicalFileName(useCaseSensitiveFileNames);
@ -649,6 +649,22 @@ import b = require("./moduleB");
});
test(files, { module: ModuleKind.CommonJS, forceConsistentCasingInFileNames: true }, "/a/B/c", /*useCaseSensitiveFileNames*/ false, ["moduleD.ts"], []);
});
it("should succeed when the two files in program differ only in drive letter in their names", () => {
const files = createMapFromTemplate({
"d:/someFolder/moduleA.ts": `import a = require("D:/someFolder/moduleC")`,
"d:/someFolder/moduleB.ts": `import a = require("./moduleC")`,
"D:/someFolder/moduleC.ts": "export const x = 10",
});
test(
files,
{ module: ModuleKind.CommonJS, forceConsistentCasingInFileNames: true },
"d:/someFolder",
/*useCaseSensitiveFileNames*/ false,
["d:/someFolder/moduleA.ts", "d:/someFolder/moduleB.ts"],
[]
);
});
});
describe("unittests:: moduleResolution:: baseUrl augmented module resolution", () => {

View File

@ -36,7 +36,7 @@ namespace ts.projectSystem {
kindModifiers: ScriptElementKindModifier.exportedModifier,
name: "foo",
replacementSpan: undefined,
sortText: "0",
sortText: Completions.SortText.AutoImportSuggestions,
source: "/a",
};
assert.deepEqual<protocol.CompletionInfo | undefined>(response, {

View File

@ -0,0 +1,64 @@
//// [ES5For-of37.ts]
// https://github.com/microsoft/TypeScript/issues/30083
for (const i of [0, 1, 2, 3, 4]) {
try {
// Ensure catch binding for the following loop is reset per iteration:
for (const j of [1, 2, 3]) {
if (i === 2) {
throw new Error('ERR');
}
}
console.log(i);
} catch (err) {
console.log('E %s %s', i, err);
}
}
//// [ES5For-of37.js]
// https://github.com/microsoft/TypeScript/issues/30083
var __values = (this && this.__values) || function (o) {
var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0;
if (m) return m.call(o);
return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
};
var e_1, _a, e_2, _b;
try {
for (var _c = __values([0, 1, 2, 3, 4]), _d = _c.next(); !_d.done; _d = _c.next()) {
var i = _d.value;
try {
try {
// Ensure catch binding for the following loop is reset per iteration:
for (var _e = (e_2 = void 0, __values([1, 2, 3])), _f = _e.next(); !_f.done; _f = _e.next()) {
var j = _f.value;
if (i === 2) {
throw new Error('ERR');
}
}
}
catch (e_2_1) { e_2 = { error: e_2_1 }; }
finally {
try {
if (_f && !_f.done && (_b = _e["return"])) _b.call(_e);
}
finally { if (e_2) throw e_2.error; }
}
console.log(i);
}
catch (err) {
console.log('E %s %s', i, err);
}
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (_d && !_d.done && (_a = _c["return"])) _a.call(_c);
}
finally { if (e_1) throw e_1.error; }
}

View File

@ -0,0 +1,35 @@
=== tests/cases/conformance/statements/for-ofStatements/ES5For-of37.ts ===
// https://github.com/microsoft/TypeScript/issues/30083
for (const i of [0, 1, 2, 3, 4]) {
>i : Symbol(i, Decl(ES5For-of37.ts, 2, 10))
try {
// Ensure catch binding for the following loop is reset per iteration:
for (const j of [1, 2, 3]) {
>j : Symbol(j, Decl(ES5For-of37.ts, 5, 18))
if (i === 2) {
>i : Symbol(i, Decl(ES5For-of37.ts, 2, 10))
throw new Error('ERR');
>Error : Symbol(Error, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --))
}
}
console.log(i);
>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, --, --))
>i : Symbol(i, Decl(ES5For-of37.ts, 2, 10))
} catch (err) {
>err : Symbol(err, Decl(ES5For-of37.ts, 11, 13))
console.log('E %s %s', i, err);
>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, --, --))
>i : Symbol(i, Decl(ES5For-of37.ts, 2, 10))
>err : Symbol(err, Decl(ES5For-of37.ts, 11, 13))
}
}

View File

@ -0,0 +1,52 @@
=== tests/cases/conformance/statements/for-ofStatements/ES5For-of37.ts ===
// https://github.com/microsoft/TypeScript/issues/30083
for (const i of [0, 1, 2, 3, 4]) {
>i : number
>[0, 1, 2, 3, 4] : number[]
>0 : 0
>1 : 1
>2 : 2
>3 : 3
>4 : 4
try {
// Ensure catch binding for the following loop is reset per iteration:
for (const j of [1, 2, 3]) {
>j : number
>[1, 2, 3] : number[]
>1 : 1
>2 : 2
>3 : 3
if (i === 2) {
>i === 2 : boolean
>i : number
>2 : 2
throw new Error('ERR');
>new Error('ERR') : Error
>Error : ErrorConstructor
>'ERR' : "ERR"
}
}
console.log(i);
>console.log(i) : void
>console.log : (message?: any, ...optionalParams: any[]) => void
>console : Console
>log : (message?: any, ...optionalParams: any[]) => void
>i : number
} catch (err) {
>err : any
console.log('E %s %s', i, err);
>console.log('E %s %s', i, err) : void
>console.log : (message?: any, ...optionalParams: any[]) => void
>console : Console
>log : (message?: any, ...optionalParams: any[]) => void
>'E %s %s' : "E %s %s"
>i : number
>err : any
}
}

View File

@ -10,4 +10,5 @@ tests/cases/conformance/statements/for-ofStatements/ES5For-of7.ts(6,9): error TS
var x = [w, v];
~
!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'x' must be of type 'any', but here has type 'any[]'.
!!! related TS6203 tests/cases/conformance/statements/for-ofStatements/ES5For-of7.ts:2:9: 'x' was also declared here.
}

View File

@ -24,6 +24,7 @@ tests/cases/conformance/internalModules/DeclarationMerging/test.ts(2,5): error T
var fn = A.Point;
~~
!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'fn' must be of type '() => { x: number; y: number; }', but here has type 'typeof Point'.
!!! related TS6203 tests/cases/conformance/internalModules/DeclarationMerging/test.ts:1:5: 'fn' was also declared here.
var cl: { x: number; y: number; }
var cl = A.Point();
@ -46,6 +47,7 @@ tests/cases/conformance/internalModules/DeclarationMerging/test.ts(2,5): error T
var fn = B.Point; // not expected to be an error. bug 840000: [corelang] Function of fundule not assignalbe as expected
~~
!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'fn' must be of type '() => { x: number; y: number; }', but here has type 'typeof Point'.
!!! related TS6203 tests/cases/conformance/internalModules/DeclarationMerging/test.ts:1:5: 'fn' was also declared here.
var cl: { x: number; y: number; }
var cl = B.Point();

View File

@ -1969,6 +1969,7 @@ declare namespace ts {
*/
getExportSymbolOfSymbol(symbol: Symbol): Symbol;
getPropertySymbolOfDestructuringAssignment(location: Identifier): Symbol | undefined;
getTypeOfAssignmentPattern(pattern: AssignmentPattern): Type;
getTypeAtLocation(node: Node): Type;
getTypeFromTypeNode(node: TypeNode): Type;
signatureToString(signature: Signature, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): string;
@ -8320,7 +8321,7 @@ declare namespace ts.server {
private readonly cancellationToken;
isNonTsProject(): boolean;
isJsOnlyProject(): boolean;
static resolveModule(moduleName: string, initialDir: string, host: ServerHost, log: (message: string) => void): {} | undefined;
static resolveModule(moduleName: string, initialDir: string, host: ServerHost, log: (message: string) => void, logErrors?: (message: string) => void): {} | undefined;
isKnownTypesPackageName(name: string): boolean;
installPackage(options: InstallPackageOptions): Promise<ApplyCodeActionCommandResult>;
private readonly typingsCache;

View File

@ -1969,6 +1969,7 @@ declare namespace ts {
*/
getExportSymbolOfSymbol(symbol: Symbol): Symbol;
getPropertySymbolOfDestructuringAssignment(location: Identifier): Symbol | undefined;
getTypeOfAssignmentPattern(pattern: AssignmentPattern): Type;
getTypeAtLocation(node: Node): Type;
getTypeFromTypeNode(node: TypeNode): Type;
signatureToString(signature: Signature, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): string;

View File

@ -16,6 +16,7 @@ tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction5_es20
!!! error TS1005: ',' expected.
~~~~~~~
!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'Promise' must be of type 'PromiseConstructor', but here has type 'any'.
!!! related TS6203 /.ts/lib.es2015.promise.d.ts:152:13: 'Promise' was also declared here.
~
!!! error TS1005: ',' expected.
~~

View File

@ -16,6 +16,7 @@ tests/cases/conformance/async/es5/asyncArrowFunction/asyncArrowFunction5_es5.ts(
!!! error TS1005: ',' expected.
~~~~~~~
!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'Promise' must be of type 'PromiseConstructor', but here has type 'any'.
!!! related TS6203 /.ts/lib.es2015.promise.d.ts:152:13: 'Promise' was also declared here.
~
!!! error TS1005: ',' expected.
~~

View File

@ -16,6 +16,7 @@ tests/cases/conformance/async/es6/asyncArrowFunction/asyncArrowFunction5_es6.ts(
!!! error TS1005: ',' expected.
~~~~~~~
!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'Promise' must be of type 'PromiseConstructor', but here has type 'any'.
!!! related TS6203 /.ts/lib.es2015.promise.d.ts:152:13: 'Promise' was also declared here.
~
!!! error TS1005: ',' expected.
~~

View File

@ -16,6 +16,7 @@ tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction9_es20
!!! error TS1005: ',' expected.
~~~~~~~
!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'Promise' must be of type 'PromiseConstructor', but here has type 'any'.
!!! related TS6203 /.ts/lib.es2015.promise.d.ts:152:13: 'Promise' was also declared here.
~
!!! error TS1005: ',' expected.
~~

View File

@ -16,6 +16,7 @@ tests/cases/conformance/async/es5/asyncArrowFunction/asyncArrowFunction9_es5.ts(
!!! error TS1005: ',' expected.
~~~~~~~
!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'Promise' must be of type 'PromiseConstructor', but here has type 'any'.
!!! related TS6203 /.ts/lib.es2015.promise.d.ts:152:13: 'Promise' was also declared here.
~
!!! error TS1005: ',' expected.
~~

View File

@ -16,6 +16,7 @@ tests/cases/conformance/async/es6/asyncArrowFunction/asyncArrowFunction9_es6.ts(
!!! error TS1005: ',' expected.
~~~~~~~
!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'Promise' must be of type 'PromiseConstructor', but here has type 'any'.
!!! related TS6203 /.ts/lib.es2015.promise.d.ts:152:13: 'Promise' was also declared here.
~
!!! error TS1005: ',' expected.
~~

View File

@ -30,6 +30,7 @@ tests/cases/compiler/augmentedTypesVar.ts(31,8): error TS2300: Duplicate identif
var x3 = () => { } // error
~~
!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'x3' must be of type 'number', but here has type '() => void'.
!!! related TS6203 tests/cases/compiler/augmentedTypesVar.ts:9:5: 'x3' was also declared here.
// var then class
var x4 = 1; // error

View File

@ -0,0 +1,15 @@
=== tests/cases/conformance/salsa/loop.js ===
var loop1 = loop2;
>loop1 : Symbol(loop1, Decl(loop.js, 0, 3))
>loop2 : Symbol(loop2, Decl(loop.js, 1, 3))
var loop2 = loop1;
>loop2 : Symbol(loop2, Decl(loop.js, 1, 3))
>loop1 : Symbol(loop1, Decl(loop.js, 0, 3))
module.exports = loop2;
>module.exports : Symbol("tests/cases/conformance/salsa/loop", Decl(loop.js, 0, 0))
>module : Symbol(export=, Decl(loop.js, 1, 18))
>exports : Symbol(export=, Decl(loop.js, 1, 18))
>loop2 : Symbol(loop2, Decl(loop.js, 1, 3))

View File

@ -0,0 +1,16 @@
=== tests/cases/conformance/salsa/loop.js ===
var loop1 = loop2;
>loop1 : any
>loop2 : any
var loop2 = loop1;
>loop2 : any
>loop1 : any
module.exports = loop2;
>module.exports = loop2 : any
>module.exports : any
>module : { "tests/cases/conformance/salsa/loop": any; }
>exports : any
>loop2 : any

View File

@ -0,0 +1,37 @@
//// [booleanFilterAnyArray.ts]
interface Bullean { }
interface BulleanConstructor {
new(v1?: any): Bullean;
<T>(v2?: T): v2 is T;
}
interface Ari<T> {
filter<S extends T>(cb1: (value: T) => value is S): T extends any ? Ari<any> : Ari<S>;
filter(cb2: (value: T) => unknown): Ari<T>;
}
declare var Bullean: BulleanConstructor;
declare let anys: Ari<any>;
var xs: Ari<any>;
var xs = anys.filter(Bullean)
declare let realanys: any[];
var ys: any[];
var ys = realanys.filter(Boolean)
var foo = [{ name: 'x' }]
var foor: Array<{name: string}>
var foor = foo.filter(x => x.name)
var foos: Array<boolean>
var foos = [true, true, false, null].filter((thing): thing is boolean => thing !== null)
//// [booleanFilterAnyArray.js]
var xs;
var xs = anys.filter(Bullean);
var ys;
var ys = realanys.filter(Boolean);
var foo = [{ name: 'x' }];
var foor;
var foor = foo.filter(function (x) { return x.name; });
var foos;
var foos = [true, true, false, null].filter(function (thing) { return thing !== null; });

View File

@ -0,0 +1,108 @@
=== tests/cases/compiler/booleanFilterAnyArray.ts ===
interface Bullean { }
>Bullean : Symbol(Bullean, Decl(booleanFilterAnyArray.ts, 0, 0), Decl(booleanFilterAnyArray.ts, 10, 11))
interface BulleanConstructor {
>BulleanConstructor : Symbol(BulleanConstructor, Decl(booleanFilterAnyArray.ts, 0, 21))
new(v1?: any): Bullean;
>v1 : Symbol(v1, Decl(booleanFilterAnyArray.ts, 2, 8))
>Bullean : Symbol(Bullean, Decl(booleanFilterAnyArray.ts, 0, 0), Decl(booleanFilterAnyArray.ts, 10, 11))
<T>(v2?: T): v2 is T;
>T : Symbol(T, Decl(booleanFilterAnyArray.ts, 3, 5))
>v2 : Symbol(v2, Decl(booleanFilterAnyArray.ts, 3, 8))
>T : Symbol(T, Decl(booleanFilterAnyArray.ts, 3, 5))
>v2 : Symbol(v2, Decl(booleanFilterAnyArray.ts, 3, 8))
>T : Symbol(T, Decl(booleanFilterAnyArray.ts, 3, 5))
}
interface Ari<T> {
>Ari : Symbol(Ari, Decl(booleanFilterAnyArray.ts, 4, 1))
>T : Symbol(T, Decl(booleanFilterAnyArray.ts, 6, 14))
filter<S extends T>(cb1: (value: T) => value is S): T extends any ? Ari<any> : Ari<S>;
>filter : Symbol(Ari.filter, Decl(booleanFilterAnyArray.ts, 6, 18), Decl(booleanFilterAnyArray.ts, 7, 90))
>S : Symbol(S, Decl(booleanFilterAnyArray.ts, 7, 11))
>T : Symbol(T, Decl(booleanFilterAnyArray.ts, 6, 14))
>cb1 : Symbol(cb1, Decl(booleanFilterAnyArray.ts, 7, 24))
>value : Symbol(value, Decl(booleanFilterAnyArray.ts, 7, 30))
>T : Symbol(T, Decl(booleanFilterAnyArray.ts, 6, 14))
>value : Symbol(value, Decl(booleanFilterAnyArray.ts, 7, 30))
>S : Symbol(S, Decl(booleanFilterAnyArray.ts, 7, 11))
>T : Symbol(T, Decl(booleanFilterAnyArray.ts, 6, 14))
>Ari : Symbol(Ari, Decl(booleanFilterAnyArray.ts, 4, 1))
>Ari : Symbol(Ari, Decl(booleanFilterAnyArray.ts, 4, 1))
>S : Symbol(S, Decl(booleanFilterAnyArray.ts, 7, 11))
filter(cb2: (value: T) => unknown): Ari<T>;
>filter : Symbol(Ari.filter, Decl(booleanFilterAnyArray.ts, 6, 18), Decl(booleanFilterAnyArray.ts, 7, 90))
>cb2 : Symbol(cb2, Decl(booleanFilterAnyArray.ts, 8, 11))
>value : Symbol(value, Decl(booleanFilterAnyArray.ts, 8, 17))
>T : Symbol(T, Decl(booleanFilterAnyArray.ts, 6, 14))
>Ari : Symbol(Ari, Decl(booleanFilterAnyArray.ts, 4, 1))
>T : Symbol(T, Decl(booleanFilterAnyArray.ts, 6, 14))
}
declare var Bullean: BulleanConstructor;
>Bullean : Symbol(Bullean, Decl(booleanFilterAnyArray.ts, 0, 0), Decl(booleanFilterAnyArray.ts, 10, 11))
>BulleanConstructor : Symbol(BulleanConstructor, Decl(booleanFilterAnyArray.ts, 0, 21))
declare let anys: Ari<any>;
>anys : Symbol(anys, Decl(booleanFilterAnyArray.ts, 11, 11))
>Ari : Symbol(Ari, Decl(booleanFilterAnyArray.ts, 4, 1))
var xs: Ari<any>;
>xs : Symbol(xs, Decl(booleanFilterAnyArray.ts, 12, 3), Decl(booleanFilterAnyArray.ts, 13, 3))
>Ari : Symbol(Ari, Decl(booleanFilterAnyArray.ts, 4, 1))
var xs = anys.filter(Bullean)
>xs : Symbol(xs, Decl(booleanFilterAnyArray.ts, 12, 3), Decl(booleanFilterAnyArray.ts, 13, 3))
>anys.filter : Symbol(Ari.filter, Decl(booleanFilterAnyArray.ts, 6, 18), Decl(booleanFilterAnyArray.ts, 7, 90))
>anys : Symbol(anys, Decl(booleanFilterAnyArray.ts, 11, 11))
>filter : Symbol(Ari.filter, Decl(booleanFilterAnyArray.ts, 6, 18), Decl(booleanFilterAnyArray.ts, 7, 90))
>Bullean : Symbol(Bullean, Decl(booleanFilterAnyArray.ts, 0, 0), Decl(booleanFilterAnyArray.ts, 10, 11))
declare let realanys: any[];
>realanys : Symbol(realanys, Decl(booleanFilterAnyArray.ts, 15, 11))
var ys: any[];
>ys : Symbol(ys, Decl(booleanFilterAnyArray.ts, 16, 3), Decl(booleanFilterAnyArray.ts, 17, 3))
var ys = realanys.filter(Boolean)
>ys : Symbol(ys, Decl(booleanFilterAnyArray.ts, 16, 3), Decl(booleanFilterAnyArray.ts, 17, 3))
>realanys.filter : Symbol(Array.filter, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --))
>realanys : Symbol(realanys, Decl(booleanFilterAnyArray.ts, 15, 11))
>filter : Symbol(Array.filter, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --))
>Boolean : Symbol(Boolean, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --))
var foo = [{ name: 'x' }]
>foo : Symbol(foo, Decl(booleanFilterAnyArray.ts, 19, 3))
>name : Symbol(name, Decl(booleanFilterAnyArray.ts, 19, 12))
var foor: Array<{name: string}>
>foor : Symbol(foor, Decl(booleanFilterAnyArray.ts, 20, 3), Decl(booleanFilterAnyArray.ts, 21, 3))
>Array : Symbol(Array, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --))
>name : Symbol(name, Decl(booleanFilterAnyArray.ts, 20, 17))
var foor = foo.filter(x => x.name)
>foor : Symbol(foor, Decl(booleanFilterAnyArray.ts, 20, 3), Decl(booleanFilterAnyArray.ts, 21, 3))
>foo.filter : Symbol(Array.filter, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --))
>foo : Symbol(foo, Decl(booleanFilterAnyArray.ts, 19, 3))
>filter : Symbol(Array.filter, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --))
>x : Symbol(x, Decl(booleanFilterAnyArray.ts, 21, 22))
>x.name : Symbol(name, Decl(booleanFilterAnyArray.ts, 19, 12))
>x : Symbol(x, Decl(booleanFilterAnyArray.ts, 21, 22))
>name : Symbol(name, Decl(booleanFilterAnyArray.ts, 19, 12))
var foos: Array<boolean>
>foos : Symbol(foos, Decl(booleanFilterAnyArray.ts, 22, 3), Decl(booleanFilterAnyArray.ts, 23, 3))
>Array : Symbol(Array, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --))
var foos = [true, true, false, null].filter((thing): thing is boolean => thing !== null)
>foos : Symbol(foos, Decl(booleanFilterAnyArray.ts, 22, 3), Decl(booleanFilterAnyArray.ts, 23, 3))
>[true, true, false, null].filter : Symbol(Array.filter, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --))
>filter : Symbol(Array.filter, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --))
>thing : Symbol(thing, Decl(booleanFilterAnyArray.ts, 23, 45))
>thing : Symbol(thing, Decl(booleanFilterAnyArray.ts, 23, 45))
>thing : Symbol(thing, Decl(booleanFilterAnyArray.ts, 23, 45))

View File

@ -0,0 +1,94 @@
=== tests/cases/compiler/booleanFilterAnyArray.ts ===
interface Bullean { }
interface BulleanConstructor {
new(v1?: any): Bullean;
>v1 : any
<T>(v2?: T): v2 is T;
>v2 : T
}
interface Ari<T> {
filter<S extends T>(cb1: (value: T) => value is S): T extends any ? Ari<any> : Ari<S>;
>filter : { <S extends T>(cb1: (value: T) => value is S): T extends any ? Ari<any> : Ari<S>; (cb2: (value: T) => unknown): Ari<T>; }
>cb1 : (value: T) => value is S
>value : T
filter(cb2: (value: T) => unknown): Ari<T>;
>filter : { <S extends T>(cb1: (value: T) => value is S): T extends any ? Ari<any> : Ari<S>; (cb2: (value: T) => unknown): Ari<T>; }
>cb2 : (value: T) => unknown
>value : T
}
declare var Bullean: BulleanConstructor;
>Bullean : BulleanConstructor
declare let anys: Ari<any>;
>anys : Ari<any>
var xs: Ari<any>;
>xs : Ari<any>
var xs = anys.filter(Bullean)
>xs : Ari<any>
>anys.filter(Bullean) : Ari<any>
>anys.filter : { <S extends any>(cb1: (value: any) => value is S): Ari<any>; (cb2: (value: any) => unknown): Ari<any>; }
>anys : Ari<any>
>filter : { <S extends any>(cb1: (value: any) => value is S): Ari<any>; (cb2: (value: any) => unknown): Ari<any>; }
>Bullean : BulleanConstructor
declare let realanys: any[];
>realanys : any[]
var ys: any[];
>ys : any[]
var ys = realanys.filter(Boolean)
>ys : any[]
>realanys.filter(Boolean) : any[]
>realanys.filter : { <S extends any>(callbackfn: (value: any, index: number, array: any[]) => value is S, thisArg?: any): S[]; (callbackfn: (value: any, index: number, array: any[]) => unknown, thisArg?: any): any[]; }
>realanys : any[]
>filter : { <S extends any>(callbackfn: (value: any, index: number, array: any[]) => value is S, thisArg?: any): S[]; (callbackfn: (value: any, index: number, array: any[]) => unknown, thisArg?: any): any[]; }
>Boolean : BooleanConstructor
var foo = [{ name: 'x' }]
>foo : { name: string; }[]
>[{ name: 'x' }] : { name: string; }[]
>{ name: 'x' } : { name: string; }
>name : string
>'x' : "x"
var foor: Array<{name: string}>
>foor : { name: string; }[]
>name : string
var foor = foo.filter(x => x.name)
>foor : { name: string; }[]
>foo.filter(x => x.name) : { name: string; }[]
>foo.filter : { <S extends { name: string; }>(callbackfn: (value: { name: string; }, index: number, array: { name: string; }[]) => value is S, thisArg?: any): S[]; (callbackfn: (value: { name: string; }, index: number, array: { name: string; }[]) => unknown, thisArg?: any): { name: string; }[]; }
>foo : { name: string; }[]
>filter : { <S extends { name: string; }>(callbackfn: (value: { name: string; }, index: number, array: { name: string; }[]) => value is S, thisArg?: any): S[]; (callbackfn: (value: { name: string; }, index: number, array: { name: string; }[]) => unknown, thisArg?: any): { name: string; }[]; }
>x => x.name : (x: { name: string; }) => string
>x : { name: string; }
>x.name : string
>x : { name: string; }
>name : string
var foos: Array<boolean>
>foos : boolean[]
var foos = [true, true, false, null].filter((thing): thing is boolean => thing !== null)
>foos : boolean[]
>[true, true, false, null].filter((thing): thing is boolean => thing !== null) : boolean[]
>[true, true, false, null].filter : { <S extends boolean>(callbackfn: (value: boolean, index: number, array: boolean[]) => value is S, thisArg?: any): S[]; (callbackfn: (value: boolean, index: number, array: boolean[]) => unknown, thisArg?: any): boolean[]; }
>[true, true, false, null] : boolean[]
>true : true
>true : true
>false : false
>null : null
>filter : { <S extends boolean>(callbackfn: (value: boolean, index: number, array: boolean[]) => value is S, thisArg?: any): S[]; (callbackfn: (value: boolean, index: number, array: boolean[]) => unknown, thisArg?: any): boolean[]; }
>(thing): thing is boolean => thing !== null : (thing: boolean) => thing is boolean
>thing : boolean
>thing !== null : boolean
>thing : boolean
>null : null

View File

@ -71,6 +71,7 @@ tests/cases/conformance/types/tuple/castingTuple.ts(33,1): error TS2304: Cannot
var array1 = <number[]>numStrTuple;
~~~~~~
!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'array1' must be of type '{}[]', but here has type 'number[]'.
!!! related TS6203 tests/cases/conformance/types/tuple/castingTuple.ts:23:5: 'array1' was also declared here.
t4[2] = 10;
~~
!!! error TS2304: Cannot find name 't4'.

View File

@ -15,6 +15,7 @@ tests/cases/compiler/global.d.ts(6,16): error TS2403: Subsequent variable declar
export const THREE: typeof _three;
~~~~~
!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'THREE' must be of type 'typeof import("tests/cases/compiler/global")', but here has type 'typeof import("tests/cases/compiler/three")'.
!!! related TS6203 tests/cases/compiler/global.d.ts:1:1: 'THREE' was also declared here.
}
==== tests/cases/compiler/test.ts (0 errors) ====

View File

@ -14,6 +14,7 @@ tests/cases/compiler/classWithDuplicateIdentifier.ts(11,5): error TS2717: Subseq
!!! error TS2300: Duplicate identifier 'a'.
~
!!! error TS2717: Subsequent property declarations must have the same type. Property 'a' must be of type '() => number', but here has type 'number'.
!!! related TS6203 tests/cases/compiler/classWithDuplicateIdentifier.ts:2:5: 'a' was also declared here.
}
class K {
b: number; // error: duplicate identifier
@ -30,5 +31,6 @@ tests/cases/compiler/classWithDuplicateIdentifier.ts(11,5): error TS2717: Subseq
!!! error TS2300: Duplicate identifier 'c'.
~
!!! error TS2717: Subsequent property declarations must have the same type. Property 'c' must be of type 'number', but here has type 'string'.
!!! related TS6203 tests/cases/compiler/classWithDuplicateIdentifier.ts:10:5: 'c' was also declared here.
}

View File

@ -0,0 +1,8 @@
//// [index.js]
module.exports = {}
var x = 1
//// [index.js]
module.exports = {};
var x = 1;

View File

@ -0,0 +1,9 @@
=== tests/cases/compiler/index.js ===
module.exports = {}
>module.exports : Symbol("tests/cases/compiler/index", Decl(index.js, 0, 0))
>module : Symbol(module, Decl(index.js, 0, 0))
>exports : Symbol("tests/cases/compiler/index", Decl(index.js, 0, 0))
var x = 1
>x : Symbol(x, Decl(index.js, 1, 3))

View File

@ -0,0 +1,12 @@
=== tests/cases/compiler/index.js ===
module.exports = {}
>module.exports = {} : typeof import("tests/cases/compiler/index")
>module.exports : typeof import("tests/cases/compiler/index")
>module : { "tests/cases/compiler/index": typeof import("tests/cases/compiler/index"); }
>exports : typeof import("tests/cases/compiler/index")
>{} : {}
var x = 1
>x : number
>1 : 1

View File

@ -391,6 +391,7 @@ tests/cases/conformance/types/conditional/conditionalTypes1.ts(288,43): error TS
var z: T2; // Error, T2 is distributive, T1 isn't
~
!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'z' must be of type 'T1', but here has type 'Foo<T & U>'.
!!! related TS6203 tests/cases/conformance/types/conditional/conditionalTypes1.ts:262:9: 'z' was also declared here.
}
function f33<T, U>() {

View File

@ -0,0 +1,45 @@
//// [tests/cases/compiler/declarationEmitForGlobalishSpecifierSymlink.ts] ////
//// [impl.d.ts]
export function getA(): A;
export enum A {
Val
}
//// [index.d.ts]
export * from "./src/impl";
//// [package.json]
{
"name": "typescript-fsa",
"version": "1.0.0"
}
//// [impl.d.ts]
export function getA(): A;
export enum A {
Val
}
//// [index.d.ts]
export * from "./src/impl";
//// [package.json]
{
"name": "typescript-fsa",
"version": "1.0.0"
}
//// [index.ts]
import * as _whatever from "p2";
import { getA } from "typescript-fsa";
export const a = getA();
//// [index.d.ts]
export const a: import("typescript-fsa").A;
//// [index.js]
"use strict";
exports.__esModule = true;
var typescript_fsa_1 = require("typescript-fsa");
exports.a = typescript_fsa_1.getA();
//// [index.d.ts]
export declare const a: import("typescript-fsa").A;

View File

@ -0,0 +1,43 @@
=== /p1/node_modules/typescript-fsa/src/impl.d.ts ===
export function getA(): A;
>getA : Symbol(getA, Decl(impl.d.ts, 0, 0))
>A : Symbol(A, Decl(impl.d.ts, 0, 26))
export enum A {
>A : Symbol(A, Decl(impl.d.ts, 0, 26))
Val
>Val : Symbol(A.Val, Decl(impl.d.ts, 1, 15))
}
=== /p1/node_modules/typescript-fsa/index.d.ts ===
export * from "./src/impl";
No type information for this code.=== /p2/node_modules/typescript-fsa/src/impl.d.ts ===
export function getA(): A;
>getA : Symbol(getA, Decl(impl.d.ts, 0, 0))
>A : Symbol(A, Decl(impl.d.ts, 0, 26))
export enum A {
>A : Symbol(A, Decl(impl.d.ts, 0, 26))
Val
>Val : Symbol(A.Val, Decl(impl.d.ts, 1, 15))
}
=== /p2/node_modules/typescript-fsa/index.d.ts ===
export * from "./src/impl";
No type information for this code.=== /p1/index.ts ===
import * as _whatever from "p2";
>_whatever : Symbol(_whatever, Decl(index.ts, 0, 6))
import { getA } from "typescript-fsa";
>getA : Symbol(getA, Decl(index.ts, 1, 8))
export const a = getA();
>a : Symbol(a, Decl(index.ts, 3, 12))
>getA : Symbol(getA, Decl(index.ts, 1, 8))
=== /p2/index.d.ts ===
export const a: import("typescript-fsa").A;
>a : Symbol(a, Decl(index.d.ts, 0, 12))
>A : Symbol(A, Decl(impl.d.ts, 0, 26))

View File

@ -0,0 +1,41 @@
=== /p1/node_modules/typescript-fsa/src/impl.d.ts ===
export function getA(): A;
>getA : () => A
export enum A {
>A : A
Val
>Val : A
}
=== /p1/node_modules/typescript-fsa/index.d.ts ===
export * from "./src/impl";
No type information for this code.=== /p2/node_modules/typescript-fsa/src/impl.d.ts ===
export function getA(): A;
>getA : () => A
export enum A {
>A : A
Val
>Val : A
}
=== /p2/node_modules/typescript-fsa/index.d.ts ===
export * from "./src/impl";
No type information for this code.=== /p1/index.ts ===
import * as _whatever from "p2";
>_whatever : typeof _whatever
import { getA } from "typescript-fsa";
>getA : () => import("/p1/node_modules/typescript-fsa/index").A
export const a = getA();
>a : import("/p1/node_modules/typescript-fsa/index").A
>getA() : import("/p1/node_modules/typescript-fsa/index").A
>getA : () => import("/p1/node_modules/typescript-fsa/index").A
=== /p2/index.d.ts ===
export const a: import("typescript-fsa").A;
>a : import("/p2/node_modules/typescript-fsa/index").A

View File

@ -0,0 +1,33 @@
//// [tests/cases/compiler/declarationEmitForGlobalishSpecifierSymlink2.ts] ////
//// [impl.d.ts]
export function getA(): A;
export enum A {
Val
}
//// [index.d.ts]
export * from "./src/impl";
//// [package.json]
{
"name": "typescript-fsa",
"version": "1.0.0"
}
//// [index.ts]
import * as _whatever from "p2";
import { getA } from "typescript-fsa";
export const a = getA();
//// [index.d.ts]
export const a: import("typescript-fsa").A;
//// [index.js]
"use strict";
exports.__esModule = true;
var typescript_fsa_1 = require("typescript-fsa");
exports.a = typescript_fsa_1.getA();
//// [index.d.ts]
export declare const a: import("typescript-fsa").A;

View File

@ -0,0 +1,30 @@
=== /cache/typescript-fsa/src/impl.d.ts ===
export function getA(): A;
>getA : Symbol(getA, Decl(impl.d.ts, 0, 0))
>A : Symbol(A, Decl(impl.d.ts, 0, 26))
export enum A {
>A : Symbol(A, Decl(impl.d.ts, 0, 26))
Val
>Val : Symbol(A.Val, Decl(impl.d.ts, 1, 15))
}
=== /cache/typescript-fsa/index.d.ts ===
export * from "./src/impl";
No type information for this code.=== /p1/index.ts ===
import * as _whatever from "p2";
>_whatever : Symbol(_whatever, Decl(index.ts, 0, 6))
import { getA } from "typescript-fsa";
>getA : Symbol(getA, Decl(index.ts, 1, 8))
export const a = getA();
>a : Symbol(a, Decl(index.ts, 3, 12))
>getA : Symbol(getA, Decl(index.ts, 1, 8))
=== /p2/index.d.ts ===
export const a: import("typescript-fsa").A;
>a : Symbol(a, Decl(index.d.ts, 0, 12))
>A : Symbol(A, Decl(impl.d.ts, 0, 26))

View File

@ -0,0 +1,29 @@
=== /cache/typescript-fsa/src/impl.d.ts ===
export function getA(): A;
>getA : () => A
export enum A {
>A : A
Val
>Val : A
}
=== /cache/typescript-fsa/index.d.ts ===
export * from "./src/impl";
No type information for this code.=== /p1/index.ts ===
import * as _whatever from "p2";
>_whatever : typeof _whatever
import { getA } from "typescript-fsa";
>getA : () => import("/cache/typescript-fsa/index").A
export const a = getA();
>a : import("/cache/typescript-fsa/index").A
>getA() : import("/cache/typescript-fsa/index").A
>getA : () => import("/cache/typescript-fsa/index").A
=== /p2/index.d.ts ===
export const a: import("typescript-fsa").A;
>a : import("/cache/typescript-fsa/index").A

View File

@ -97,6 +97,7 @@ tests/cases/conformance/es6/destructuring/declarationsAndAssignments.ts(138,9):
var y: string;
~
!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'y' must be of type 'string | number', but here has type 'string'.
!!! related TS6203 tests/cases/conformance/es6/destructuring/declarationsAndAssignments.ts:56:17: 'y' was also declared here.
}
function f8() {

View File

@ -97,6 +97,7 @@ tests/cases/compiler/duplicateClassElements.ts(41,12): error TS2300: Duplicate i
!!! error TS2300: Duplicate identifier 'x2'.
~~
!!! error TS2717: Subsequent property declarations must have the same type. Property 'x2' must be of type 'number', but here has type 'any'.
!!! related TS6203 tests/cases/compiler/duplicateClassElements.ts:29:9: 'x2' was also declared here.
get z2() {
~~

View File

@ -38,4 +38,5 @@ tests/cases/compiler/duplicateIdentifierInCatchBlock.ts(16,9): error TS2403: Sub
var p: number; // error
~
!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'p' must be of type 'string', but here has type 'number'.
!!! related TS6203 tests/cases/compiler/duplicateIdentifierInCatchBlock.ts:15:9: 'p' was also declared here.
}

View File

@ -201,6 +201,7 @@ tests/cases/compiler/duplicateLocalVariable1.ts(186,37): error TS2356: An arithm
for (var i = 0; i < 14; i++) {
~
!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'i' must be of type 'string', but here has type 'number'.
!!! related TS6203 tests/cases/compiler/duplicateLocalVariable1.ts:181:22: 'i' was also declared here.
~~~~~~
!!! error TS2365: Operator '<' cannot be applied to types 'string' and 'number'.
~

View File

@ -33,6 +33,7 @@ tests/cases/compiler/duplicateLocalVariable2.ts(27,37): error TS2356: An arithme
for (var i = 0; i < 14; i++) {
~
!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'i' must be of type 'string', but here has type 'number'.
!!! related TS6203 tests/cases/compiler/duplicateLocalVariable2.ts:22:22: 'i' was also declared here.
~~~~~~
!!! error TS2365: Operator '<' cannot be applied to types 'string' and 'number'.
~

View File

@ -15,4 +15,5 @@ tests/cases/compiler/duplicateLocalVariable3.ts(11,9): error TS2403: Subsequent
var z = "";
~
!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'z' must be of type 'number', but here has type 'string'.
!!! related TS6203 tests/cases/compiler/duplicateLocalVariable3.ts:10:9: 'z' was also declared here.
}

View File

@ -9,4 +9,5 @@ tests/cases/compiler/duplicateLocalVariable4.ts(6,5): error TS2403: Subsequent v
var x = E;
var x = E.a;
~
!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'x' must be of type 'typeof E', but here has type 'E'.
!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'x' must be of type 'typeof E', but here has type 'E'.
!!! related TS6203 tests/cases/compiler/duplicateLocalVariable4.ts:5:5: 'x' was also declared here.

View File

@ -2,13 +2,13 @@
"======== Resolving module 'foo/use' from '/index.ts'. ========",
"Module resolution kind is not specified, using 'NodeJs'.",
"Loading module 'foo/use' from 'node_modules' folder, target file type 'TypeScript'.",
"Found 'package.json' at '/node_modules/foo/package.json'.",
"'package.json' does not have a 'typesVersions' field.",
"Found 'package.json' at '/node_modules/foo/package.json'. Package ID is 'foo/use/index.d.ts@1.2.3'.",
"File '/node_modules/foo/use.ts' does not exist.",
"File '/node_modules/foo/use.tsx' does not exist.",
"File '/node_modules/foo/use.d.ts' exist - use it as a name resolution result.",
"Resolving real path for '/node_modules/foo/use.d.ts', result '/node_modules/foo/use.d.ts'.",
"======== Module name 'foo/use' was successfully resolved to '/node_modules/foo/use.d.ts'. ========",
"======== Module name 'foo/use' was successfully resolved to '/node_modules/foo/use.d.ts' with Package ID 'foo/use.d.ts@1.2.3'. ========",
"======== Resolving module 'a' from '/index.ts'. ========",
"Module resolution kind is not specified, using 'NodeJs'.",
"Loading module 'a' from 'node_modules' folder, target file type 'TypeScript'.",
@ -27,17 +27,14 @@
"File '/node_modules/foo/index.ts' does not exist.",
"File '/node_modules/foo/index.tsx' does not exist.",
"File '/node_modules/foo/index.d.ts' exist - use it as a name resolution result.",
"Found 'package.json' at '/node_modules/foo/package.json'.",
"'package.json' does not have a 'typesVersions' field.",
"Found 'package.json' at '/node_modules/foo/package.json'. Package ID is 'foo/index.d.ts@1.2.3'.",
"======== Module name './index' was successfully resolved to '/node_modules/foo/index.d.ts'. ========",
"======== Module name './index' was successfully resolved to '/node_modules/foo/index.d.ts' with Package ID 'foo/index.d.ts@1.2.3'. ========",
"======== Resolving module 'foo' from '/node_modules/a/index.d.ts'. ========",
"Module resolution kind is not specified, using 'NodeJs'.",
"Loading module 'foo' from 'node_modules' folder, target file type 'TypeScript'.",
"'package.json' does not have a 'typings' field.",
"'package.json' does not have a 'types' field.",
"'package.json' does not have a 'main' field.",
"Found 'package.json' at '/node_modules/a/node_modules/foo/package.json'.",
"'package.json' does not have a 'typesVersions' field.",
"Found 'package.json' at '/node_modules/a/node_modules/foo/package.json'. Package ID is 'foo/index.d.ts@1.2.3'.",
"File '/node_modules/a/node_modules/foo.ts' does not exist.",
"File '/node_modules/a/node_modules/foo.tsx' does not exist.",
"File '/node_modules/a/node_modules/foo.d.ts' does not exist.",
@ -48,5 +45,5 @@
"File '/node_modules/a/node_modules/foo/index.tsx' does not exist.",
"File '/node_modules/a/node_modules/foo/index.d.ts' exist - use it as a name resolution result.",
"Resolving real path for '/node_modules/a/node_modules/foo/index.d.ts', result '/node_modules/a/node_modules/foo/index.d.ts'.",
"======== Module name 'foo' was successfully resolved to '/node_modules/a/node_modules/foo/index.d.ts'. ========"
"======== Module name 'foo' was successfully resolved to '/node_modules/a/node_modules/foo/index.d.ts' with Package ID 'foo/index.d.ts@1.2.3'. ========"
]

View File

@ -2,13 +2,13 @@
"======== Resolving module '@foo/bar/use' from '/index.ts'. ========",
"Module resolution kind is not specified, using 'NodeJs'.",
"Loading module '@foo/bar/use' from 'node_modules' folder, target file type 'TypeScript'.",
"Found 'package.json' at '/node_modules/@foo/bar/package.json'.",
"'package.json' does not have a 'typesVersions' field.",
"Found 'package.json' at '/node_modules/@foo/bar/package.json'. Package ID is '@foo/bar/use/index.d.ts@1.2.3'.",
"File '/node_modules/@foo/bar/use.ts' does not exist.",
"File '/node_modules/@foo/bar/use.tsx' does not exist.",
"File '/node_modules/@foo/bar/use.d.ts' exist - use it as a name resolution result.",
"Resolving real path for '/node_modules/@foo/bar/use.d.ts', result '/node_modules/@foo/bar/use.d.ts'.",
"======== Module name '@foo/bar/use' was successfully resolved to '/node_modules/@foo/bar/use.d.ts'. ========",
"======== Module name '@foo/bar/use' was successfully resolved to '/node_modules/@foo/bar/use.d.ts' with Package ID '@foo/bar/use.d.ts@1.2.3'. ========",
"======== Resolving module 'a' from '/index.ts'. ========",
"Module resolution kind is not specified, using 'NodeJs'.",
"Loading module 'a' from 'node_modules' folder, target file type 'TypeScript'.",
@ -27,17 +27,14 @@
"File '/node_modules/@foo/bar/index.ts' does not exist.",
"File '/node_modules/@foo/bar/index.tsx' does not exist.",
"File '/node_modules/@foo/bar/index.d.ts' exist - use it as a name resolution result.",
"Found 'package.json' at '/node_modules/@foo/bar/package.json'.",
"'package.json' does not have a 'typesVersions' field.",
"Found 'package.json' at '/node_modules/@foo/bar/package.json'. Package ID is '@foo/bar/index.d.ts@1.2.3'.",
"======== Module name './index' was successfully resolved to '/node_modules/@foo/bar/index.d.ts'. ========",
"======== Module name './index' was successfully resolved to '/node_modules/@foo/bar/index.d.ts' with Package ID '@foo/bar/index.d.ts@1.2.3'. ========",
"======== Resolving module '@foo/bar' from '/node_modules/a/index.d.ts'. ========",
"Module resolution kind is not specified, using 'NodeJs'.",
"Loading module '@foo/bar' from 'node_modules' folder, target file type 'TypeScript'.",
"'package.json' does not have a 'typings' field.",
"'package.json' does not have a 'types' field.",
"'package.json' does not have a 'main' field.",
"Found 'package.json' at '/node_modules/a/node_modules/@foo/bar/package.json'.",
"'package.json' does not have a 'typesVersions' field.",
"Found 'package.json' at '/node_modules/a/node_modules/@foo/bar/package.json'. Package ID is '@foo/bar/index.d.ts@1.2.3'.",
"File '/node_modules/a/node_modules/@foo/bar.ts' does not exist.",
"File '/node_modules/a/node_modules/@foo/bar.tsx' does not exist.",
"File '/node_modules/a/node_modules/@foo/bar.d.ts' does not exist.",
@ -48,5 +45,5 @@
"File '/node_modules/a/node_modules/@foo/bar/index.tsx' does not exist.",
"File '/node_modules/a/node_modules/@foo/bar/index.d.ts' exist - use it as a name resolution result.",
"Resolving real path for '/node_modules/a/node_modules/@foo/bar/index.d.ts', result '/node_modules/a/node_modules/@foo/bar/index.d.ts'.",
"======== Module name '@foo/bar' was successfully resolved to '/node_modules/a/node_modules/@foo/bar/index.d.ts'. ========"
"======== Module name '@foo/bar' was successfully resolved to '/node_modules/a/node_modules/@foo/bar/index.d.ts' with Package ID '@foo/bar/index.d.ts@1.2.3'. ========"
]

View File

@ -10,22 +10,26 @@ tests/cases/compiler/duplicateVariablesWithAny.ts(13,9): error TS2403: Subsequen
var x = 2; //error
~
!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'x' must be of type 'any', but here has type 'number'.
!!! related TS6203 tests/cases/compiler/duplicateVariablesWithAny.ts:2:5: 'x' was also declared here.
var y = "";
var y; //error
~
!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'y' must be of type 'string', but here has type 'any'.
!!! related TS6203 tests/cases/compiler/duplicateVariablesWithAny.ts:5:5: 'y' was also declared here.
module N {
var x: any;
var x = 2; //error
~
!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'x' must be of type 'any', but here has type 'number'.
!!! related TS6203 tests/cases/compiler/duplicateVariablesWithAny.ts:9:9: 'x' was also declared here.
var y = "";
var y; //error
~
!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'y' must be of type 'string', but here has type 'any'.
!!! related TS6203 tests/cases/compiler/duplicateVariablesWithAny.ts:12:9: 'y' was also declared here.
}
var z: any;

View File

@ -12,18 +12,22 @@ tests/cases/compiler/duplicateVarsAcrossFileBoundaries_2.ts(3,5): error TS2403:
var x = true;
~
!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'x' must be of type 'number', but here has type 'boolean'.
!!! related TS6203 tests/cases/compiler/duplicateVarsAcrossFileBoundaries_0.ts:1:5: 'x' was also declared here.
var z = 3;
==== tests/cases/compiler/duplicateVarsAcrossFileBoundaries_2.ts (3 errors) ====
var x = "";
~
!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'x' must be of type 'number', but here has type 'string'.
!!! related TS6203 tests/cases/compiler/duplicateVarsAcrossFileBoundaries_0.ts:1:5: 'x' was also declared here.
var y = 3;
~
!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'y' must be of type 'string', but here has type 'number'.
!!! related TS6203 tests/cases/compiler/duplicateVarsAcrossFileBoundaries_0.ts:2:5: 'y' was also declared here.
var z = false;
~
!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'z' must be of type 'number', but here has type 'boolean'.
!!! related TS6203 tests/cases/compiler/duplicateVarsAcrossFileBoundaries_1.ts:2:5: 'z' was also declared here.
==== tests/cases/compiler/duplicateVarsAcrossFileBoundaries_3.ts (0 errors) ====
var x = 0;

View File

@ -35,6 +35,7 @@ tests/cases/compiler/dynamicNamesErrors.ts(25,1): error TS2322: Type 'T1' is not
[c1]: string;
~~~~
!!! error TS2717: Subsequent property declarations must have the same type. Property '[c1]' must be of type 'number', but here has type 'string'.
!!! related TS6203 tests/cases/compiler/dynamicNamesErrors.ts:18:5: '[c1]' was also declared here.
}
let t1: T1;

View File

@ -109,10 +109,12 @@ tests/cases/conformance/types/typeRelationships/assignmentCompatibility/enumAssi
var r4 = foo16(E.A);
~~
!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'r4' must be of type 'E', but here has type 'Object'.
!!! related TS6203 tests/cases/conformance/types/typeRelationships/assignmentCompatibility/enumAssignabilityInInheritance.ts:22:5: 'r4' was also declared here.
declare function foo17(x: {}): {};
declare function foo17(x: E): E;
var r4 = foo16(E.A);
~~
!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'r4' must be of type 'E', but here has type 'Object'.
!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'r4' must be of type 'E', but here has type 'Object'.
!!! related TS6203 tests/cases/conformance/types/typeRelationships/assignmentCompatibility/enumAssignabilityInInheritance.ts:22:5: 'r4' was also declared here.

View File

@ -39,6 +39,7 @@ tests/cases/conformance/statements/for-inStatements/for-inStatements.ts(79,15):
for (var x in this) { }
~
!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'x' must be of type 'string', but here has type 'Extract<keyof this, string>'.
!!! related TS6203 tests/cases/conformance/statements/for-inStatements/for-inStatements.ts:31:18: 'x' was also declared here.
return null;
}
@ -58,6 +59,7 @@ tests/cases/conformance/statements/for-inStatements/for-inStatements.ts(79,15):
for (var x in this) { }
~
!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'x' must be of type 'string', but here has type 'Extract<keyof this, string>'.
!!! related TS6203 tests/cases/conformance/statements/for-inStatements/for-inStatements.ts:48:18: 'x' was also declared here.
for (var x in super.biz) { }
for (var x in super.biz()) { }

View File

@ -29,11 +29,13 @@ tests/cases/conformance/statements/for-inStatements/for-inStatementsArrayErrors.
for (var i in a ) {
~
!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'i' must be of type 'number', but here has type 'string'.
!!! related TS6203 tests/cases/conformance/statements/for-inStatements/for-inStatementsArrayErrors.ts:11:5: 'i' was also declared here.
}
var j: any;
for (var j in a ) {
~
!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'j' must be of type 'any', but here has type 'string'.
!!! related TS6203 tests/cases/conformance/statements/for-inStatements/for-inStatementsArrayErrors.ts:15:5: 'j' was also declared here.
}

View File

@ -73,6 +73,7 @@ tests/cases/conformance/statements/for-inStatements/for-inStatementsInvalid.ts(6
for (var x in this) { }
~
!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'x' must be of type 'string', but here has type 'Extract<keyof this, string>'.
!!! related TS6203 tests/cases/conformance/statements/for-inStatements/for-inStatementsInvalid.ts:29:18: 'x' was also declared here.
return null;
}
@ -96,6 +97,7 @@ tests/cases/conformance/statements/for-inStatements/for-inStatementsInvalid.ts(6
for (var x in this) { }
~
!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'x' must be of type 'string', but here has type 'Extract<keyof this, string>'.
!!! related TS6203 tests/cases/conformance/statements/for-inStatements/for-inStatementsInvalid.ts:46:18: 'x' was also declared here.
for (var x in super.biz) { }
for (var x in super.biz()) { }

View File

@ -47,46 +47,58 @@ tests/cases/conformance/statements/forStatements/forStatementsMultipleInvalidDec
for( var a = 1;;){}
~
!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'a' must be of type 'any', but here has type 'number'.
!!! related TS6203 tests/cases/conformance/statements/forStatements/forStatementsMultipleInvalidDecl.ts:31:10: 'a' was also declared here.
for( var a = 'a string';;){}
~
!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'a' must be of type 'any', but here has type 'string'.
!!! related TS6203 tests/cases/conformance/statements/forStatements/forStatementsMultipleInvalidDecl.ts:31:10: 'a' was also declared here.
for( var a = new C();;){}
~
!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'a' must be of type 'any', but here has type 'C'.
!!! related TS6203 tests/cases/conformance/statements/forStatements/forStatementsMultipleInvalidDecl.ts:31:10: 'a' was also declared here.
for( var a = new D<string>();;){}
~
!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'a' must be of type 'any', but here has type 'D<string>'.
!!! related TS6203 tests/cases/conformance/statements/forStatements/forStatementsMultipleInvalidDecl.ts:31:10: 'a' was also declared here.
for( var a = M;;){}
~
!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'a' must be of type 'any', but here has type 'typeof M'.
!!! related TS6203 tests/cases/conformance/statements/forStatements/forStatementsMultipleInvalidDecl.ts:31:10: 'a' was also declared here.
for( var b: I;;){}
for( var b = new C();;){}
~
!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'b' must be of type 'I', but here has type 'C'.
!!! related TS6203 tests/cases/conformance/statements/forStatements/forStatementsMultipleInvalidDecl.ts:38:10: 'b' was also declared here.
for( var b = new C2();;){}
~
!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'b' must be of type 'I', but here has type 'C2'.
!!! related TS6203 tests/cases/conformance/statements/forStatements/forStatementsMultipleInvalidDecl.ts:38:10: 'b' was also declared here.
for(var f = F;;){}
for( var f = (x: number) => '';;){}
~
!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'f' must be of type '(x: string) => number', but here has type '(x: number) => string'.
!!! related TS6203 tests/cases/conformance/statements/forStatements/forStatementsMultipleInvalidDecl.ts:42:9: 'f' was also declared here.
for(var arr: string[];;){}
for( var arr = [1, 2, 3, 4];;){}
~~~
!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'arr' must be of type 'string[]', but here has type 'number[]'.
!!! related TS6203 tests/cases/conformance/statements/forStatements/forStatementsMultipleInvalidDecl.ts:45:9: 'arr' was also declared here.
for( var arr = [new C(), new C2(), new D<string>()];;){}
~~~
!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'arr' must be of type 'string[]', but here has type '(C | D<string>)[]'.
!!! related TS6203 tests/cases/conformance/statements/forStatements/forStatementsMultipleInvalidDecl.ts:45:9: 'arr' was also declared here.
for(var arr2 = [new D<string>()];;){}
for( var arr2 = new Array<D<number>>();;){}
~~~~
!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'arr2' must be of type 'D<string>[]', but here has type 'D<number>[]'.
!!! related TS6203 tests/cases/conformance/statements/forStatements/forStatementsMultipleInvalidDecl.ts:49:9: 'arr2' was also declared here.
for(var m: typeof M;;){}
for( var m = M.A;;){}
~
!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'm' must be of type 'typeof M', but here has type 'typeof A'.
!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'm' must be of type 'typeof M', but here has type 'typeof A'.
!!! related TS6203 tests/cases/conformance/statements/forStatements/forStatementsMultipleInvalidDecl.ts:52:9: 'm' was also declared here.

View File

@ -10,6 +10,7 @@ tests/cases/compiler/functionArgShadowing.ts(10,7): error TS2403: Subsequent var
var x: B = new B();
~
!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'x' must be of type 'A', but here has type 'B'.
!!! related TS6203 tests/cases/compiler/functionArgShadowing.ts:3:14: 'x' was also declared here.
x.bar(); // the property bar does not exist on a value of type A
~~~
!!! error TS2339: Property 'bar' does not exist on type 'A'.
@ -20,6 +21,7 @@ tests/cases/compiler/functionArgShadowing.ts(10,7): error TS2403: Subsequent var
var p: string;
~
!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'p' must be of type 'number', but here has type 'string'.
!!! related TS6203 tests/cases/compiler/functionArgShadowing.ts:9:14: 'p' was also declared here.
var n: number = p;
}

View File

@ -24,6 +24,7 @@ tests/cases/compiler/gettersAndSettersErrors.ts(12,16): error TS2379: Getter and
!!! error TS2300: Duplicate identifier 'Foo'.
~~~
!!! error TS2717: Subsequent property declarations must have the same type. Property 'Foo' must be of type 'string', but here has type 'number'.
!!! related TS6203 tests/cases/compiler/gettersAndSettersErrors.ts:2:16: 'Foo' was also declared here.
public get Goo(v:string):string {return null;} // error - getters must not have a parameter
~~~
!!! error TS1056: Accessors are only available when targeting ECMAScript 5 and higher.

View File

@ -2,8 +2,10 @@ tests/cases/conformance/es2019/globalThisUnknownNoImplicitAny.ts(4,5): error TS2
tests/cases/conformance/es2019/globalThisUnknownNoImplicitAny.ts(5,6): error TS7017: Element implicitly has an 'any' type because type 'typeof globalThis' has no index signature.
tests/cases/conformance/es2019/globalThisUnknownNoImplicitAny.ts(6,12): error TS7017: Element implicitly has an 'any' type because type 'typeof globalThis' has no index signature.
tests/cases/conformance/es2019/globalThisUnknownNoImplicitAny.ts(8,5): error TS7015: Element implicitly has an 'any' type because index expression is not of type 'number'.
tests/cases/conformance/es2019/globalThisUnknownNoImplicitAny.ts(9,1): error TS7017: Element implicitly has an 'any' type because type 'typeof globalThis' has no index signature.
tests/cases/conformance/es2019/globalThisUnknownNoImplicitAny.ts(10,1): error TS7017: Element implicitly has an 'any' type because type 'typeof globalThis' has no index signature.
tests/cases/conformance/es2019/globalThisUnknownNoImplicitAny.ts(9,1): error TS7053: Element implicitly has an 'any' type because expression of type '"hi"' can't be used to index type 'typeof globalThis'.
Property 'hi' does not exist on type 'typeof globalThis'.
tests/cases/conformance/es2019/globalThisUnknownNoImplicitAny.ts(10,1): error TS7053: Element implicitly has an 'any' type because expression of type '"hi"' can't be used to index type 'typeof globalThis'.
Property 'hi' does not exist on type 'typeof globalThis'.
==== tests/cases/conformance/es2019/globalThisUnknownNoImplicitAny.ts (6 errors) ====
@ -25,8 +27,10 @@ tests/cases/conformance/es2019/globalThisUnknownNoImplicitAny.ts(10,1): error TS
!!! error TS7015: Element implicitly has an 'any' type because index expression is not of type 'number'.
this['hi']
~~~~~~~~~~
!!! error TS7017: Element implicitly has an 'any' type because type 'typeof globalThis' has no index signature.
!!! error TS7053: Element implicitly has an 'any' type because expression of type '"hi"' can't be used to index type 'typeof globalThis'.
!!! error TS7053: Property 'hi' does not exist on type 'typeof globalThis'.
globalThis['hi']
~~~~~~~~~~~~~~~~
!!! error TS7017: Element implicitly has an 'any' type because type 'typeof globalThis' has no index signature.
!!! error TS7053: Element implicitly has an 'any' type because expression of type '"hi"' can't be used to index type 'typeof globalThis'.
!!! error TS7053: Property 'hi' does not exist on type 'typeof globalThis'.

View File

@ -12,18 +12,22 @@ tests/cases/compiler/identityForSignaturesWithTypeParametersAndAny.ts(14,5): err
var g: <T>(x: any, y: any) => any;
~
!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'g' must be of type '<T, U>(x: T, y: U) => T', but here has type '<T>(x: any, y: any) => any'.
!!! related TS6203 tests/cases/compiler/identityForSignaturesWithTypeParametersAndAny.ts:4:5: 'g' was also declared here.
var h: <T, U>(x: T, y: U) => T;
var h: (x: any, y: any) => any;
~
!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'h' must be of type '<T, U>(x: T, y: U) => T', but here has type '(x: any, y: any) => any'.
!!! related TS6203 tests/cases/compiler/identityForSignaturesWithTypeParametersAndAny.ts:7:5: 'h' was also declared here.
var i: <T, U>(x: T, y: U) => T;
var i: <T, U>(x: any, y: string) => any;
~
!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'i' must be of type '<T, U>(x: T, y: U) => T', but here has type '<T, U>(x: any, y: string) => any'.
!!! related TS6203 tests/cases/compiler/identityForSignaturesWithTypeParametersAndAny.ts:10:5: 'i' was also declared here.
var j: <T, U>(x: T, y: U) => T;
var j: <T, U>(x: any, y: any) => string;
~
!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'j' must be of type '<T, U>(x: T, y: U) => T', but here has type '<T, U>(x: any, y: any) => string'.
!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'j' must be of type '<T, U>(x: T, y: U) => T', but here has type '<T, U>(x: any, y: any) => string'.
!!! related TS6203 tests/cases/compiler/identityForSignaturesWithTypeParametersAndAny.ts:13:5: 'j' was also declared here.

View File

@ -1,4 +1,4 @@
tests/cases/compiler/script.ts(1,1): error TS1208: Cannot compile namespaces when the '--isolatedModules' flag is provided.
tests/cases/compiler/script.ts(1,1): error TS1208: All files must be modules when the '--isolatedModules' flag is provided.
==== tests/cases/compiler/external.ts (0 errors) ====
@ -16,7 +16,7 @@ tests/cases/compiler/script.ts(1,1): error TS1208: Cannot compile namespaces whe
==== tests/cases/compiler/script.ts (1 errors) ====
class A { }
~~~~~
!!! error TS1208: Cannot compile namespaces when the '--isolatedModules' flag is provided.
!!! error TS1208: All files must be modules when the '--isolatedModules' flag is provided.
class B extends A { }
declare var dec: any;

View File

@ -0,0 +1,22 @@
//// [instanceMemberWithComputedPropertyName.ts]
// https://github.com/microsoft/TypeScript/issues/30953
const x = 1;
class C {
[x] = true;
constructor() {
const { a, b } = { a: 1, b: 2 };
}
}
//// [instanceMemberWithComputedPropertyName.js]
var _a;
// https://github.com/microsoft/TypeScript/issues/30953
var x = 1;
var C = /** @class */ (function () {
function C() {
this[_a] = true;
var _b = { a: 1, b: 2 }, a = _b.a, b = _b.b;
}
return C;
}());
_a = x;

View File

@ -0,0 +1,20 @@
=== tests/cases/conformance/classes/propertyMemberDeclarations/instanceMemberWithComputedPropertyName.ts ===
// https://github.com/microsoft/TypeScript/issues/30953
const x = 1;
>x : Symbol(x, Decl(instanceMemberWithComputedPropertyName.ts, 1, 5))
class C {
>C : Symbol(C, Decl(instanceMemberWithComputedPropertyName.ts, 1, 12))
[x] = true;
>[x] : Symbol(C[x], Decl(instanceMemberWithComputedPropertyName.ts, 2, 9))
>x : Symbol(x, Decl(instanceMemberWithComputedPropertyName.ts, 1, 5))
constructor() {
const { a, b } = { a: 1, b: 2 };
>a : Symbol(a, Decl(instanceMemberWithComputedPropertyName.ts, 5, 15))
>b : Symbol(b, Decl(instanceMemberWithComputedPropertyName.ts, 5, 18))
>a : Symbol(a, Decl(instanceMemberWithComputedPropertyName.ts, 5, 26))
>b : Symbol(b, Decl(instanceMemberWithComputedPropertyName.ts, 5, 32))
}
}

View File

@ -0,0 +1,25 @@
=== tests/cases/conformance/classes/propertyMemberDeclarations/instanceMemberWithComputedPropertyName.ts ===
// https://github.com/microsoft/TypeScript/issues/30953
const x = 1;
>x : 1
>1 : 1
class C {
>C : C
[x] = true;
>[x] : boolean
>x : 1
>true : true
constructor() {
const { a, b } = { a: 1, b: 2 };
>a : number
>b : number
>{ a: 1, b: 2 } : { a: number; b: number; }
>a : number
>1 : 1
>b : number
>2 : 2
}
}

View File

@ -30,6 +30,7 @@ tests/cases/compiler/interfaceDeclaration1.ts(52,11): error TS2320: Interface 'i
!!! error TS2300: Duplicate identifier 'item'.
~~~~
!!! error TS2717: Subsequent property declarations must have the same type. Property 'item' must be of type 'any', but here has type 'number'.
!!! related TS6203 tests/cases/compiler/interfaceDeclaration1.ts:7:5: 'item' was also declared here.
}
interface I3 {

View File

@ -10,7 +10,7 @@ tests/cases/compiler/intersectionsOfLargeUnions2.ts(31,15): error TS2536: Type '
interface ElementTagNameMap {
~~~~~~~~~~~~~~~~~
!!! error TS2300: Duplicate identifier 'ElementTagNameMap'.
!!! related TS6203 /.ts/lib.dom.d.ts:18109:6: 'ElementTagNameMap' was also declared here.
!!! related TS6203 /.ts/lib.dom.d.ts:18110:6: 'ElementTagNameMap' was also declared here.
[index: number]: HTMLElement
}

View File

@ -47,46 +47,58 @@ tests/cases/conformance/statements/VariableStatements/invalidMultipleVariableDec
var a = 1;
~
!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'a' must be of type 'any', but here has type 'number'.
!!! related TS6203 tests/cases/conformance/statements/VariableStatements/invalidMultipleVariableDeclarations.ts:31:5: 'a' was also declared here.
var a = 'a string';
~
!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'a' must be of type 'any', but here has type 'string'.
!!! related TS6203 tests/cases/conformance/statements/VariableStatements/invalidMultipleVariableDeclarations.ts:31:5: 'a' was also declared here.
var a = new C();
~
!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'a' must be of type 'any', but here has type 'C'.
!!! related TS6203 tests/cases/conformance/statements/VariableStatements/invalidMultipleVariableDeclarations.ts:31:5: 'a' was also declared here.
var a = new D<string>();
~
!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'a' must be of type 'any', but here has type 'D<string>'.
!!! related TS6203 tests/cases/conformance/statements/VariableStatements/invalidMultipleVariableDeclarations.ts:31:5: 'a' was also declared here.
var a = M;
~
!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'a' must be of type 'any', but here has type 'typeof M'.
!!! related TS6203 tests/cases/conformance/statements/VariableStatements/invalidMultipleVariableDeclarations.ts:31:5: 'a' was also declared here.
var b: I;
var b = new C();
~
!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'b' must be of type 'I', but here has type 'C'.
!!! related TS6203 tests/cases/conformance/statements/VariableStatements/invalidMultipleVariableDeclarations.ts:38:5: 'b' was also declared here.
var b = new C2();
~
!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'b' must be of type 'I', but here has type 'C2'.
!!! related TS6203 tests/cases/conformance/statements/VariableStatements/invalidMultipleVariableDeclarations.ts:38:5: 'b' was also declared here.
var f = F;
var f = (x: number) => '';
~
!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'f' must be of type '(x: string) => number', but here has type '(x: number) => string'.
!!! related TS6203 tests/cases/conformance/statements/VariableStatements/invalidMultipleVariableDeclarations.ts:42:5: 'f' was also declared here.
var arr: string[];
var arr = [1, 2, 3, 4];
~~~
!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'arr' must be of type 'string[]', but here has type 'number[]'.
!!! related TS6203 tests/cases/conformance/statements/VariableStatements/invalidMultipleVariableDeclarations.ts:45:5: 'arr' was also declared here.
var arr = [new C(), new C2(), new D<string>()];
~~~
!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'arr' must be of type 'string[]', but here has type '(C | D<string>)[]'.
!!! related TS6203 tests/cases/conformance/statements/VariableStatements/invalidMultipleVariableDeclarations.ts:45:5: 'arr' was also declared here.
var arr2 = [new D<string>()];
var arr2 = new Array<D<number>>();
~~~~
!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'arr2' must be of type 'D<string>[]', but here has type 'D<number>[]'.
!!! related TS6203 tests/cases/conformance/statements/VariableStatements/invalidMultipleVariableDeclarations.ts:49:5: 'arr2' was also declared here.
var m: typeof M;
var m = M.A;
~
!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'm' must be of type 'typeof M', but here has type 'typeof A'.
!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'm' must be of type 'typeof M', but here has type 'typeof A'.
!!! related TS6203 tests/cases/conformance/statements/VariableStatements/invalidMultipleVariableDeclarations.ts:52:5: 'm' was also declared here.

View File

@ -1,7 +1,7 @@
tests/cases/compiler/file1.ts(1,1): error TS1208: Cannot compile namespaces when the '--isolatedModules' flag is provided.
tests/cases/compiler/file1.ts(1,1): error TS1208: All files must be modules when the '--isolatedModules' flag is provided.
==== tests/cases/compiler/file1.ts (1 errors) ====
var x;
~~~
!!! error TS1208: Cannot compile namespaces when the '--isolatedModules' flag is provided.
!!! error TS1208: All files must be modules when the '--isolatedModules' flag is provided.

View File

@ -1,6 +1,6 @@
error TS5053: Option 'out' cannot be specified with option 'isolatedModules'.
tests/cases/compiler/file1.ts(1,1): error TS6131: Cannot compile modules using option 'out' unless the '--module' flag is 'amd' or 'system'.
tests/cases/compiler/file2.ts(1,1): error TS1208: Cannot compile namespaces when the '--isolatedModules' flag is provided.
tests/cases/compiler/file2.ts(1,1): error TS1208: All files must be modules when the '--isolatedModules' flag is provided.
!!! error TS5053: Option 'out' cannot be specified with option 'isolatedModules'.
@ -11,4 +11,4 @@ tests/cases/compiler/file2.ts(1,1): error TS1208: Cannot compile namespaces when
==== tests/cases/compiler/file2.ts (1 errors) ====
var y;
~~~
!!! error TS1208: Cannot compile namespaces when the '--isolatedModules' flag is provided.
!!! error TS1208: All files must be modules when the '--isolatedModules' flag is provided.

View File

@ -1,9 +1,9 @@
tests/cases/compiler/isolatedModulesPlainFile-AMD.ts(1,1): error TS1208: Cannot compile namespaces when the '--isolatedModules' flag is provided.
tests/cases/compiler/isolatedModulesPlainFile-AMD.ts(1,1): error TS1208: All files must be modules when the '--isolatedModules' flag is provided.
==== tests/cases/compiler/isolatedModulesPlainFile-AMD.ts (1 errors) ====
declare function run(a: number): void;
~~~~~~~
!!! error TS1208: Cannot compile namespaces when the '--isolatedModules' flag is provided.
!!! error TS1208: All files must be modules when the '--isolatedModules' flag is provided.
run(1);

View File

@ -1,9 +1,9 @@
tests/cases/compiler/isolatedModulesPlainFile-CommonJS.ts(1,1): error TS1208: Cannot compile namespaces when the '--isolatedModules' flag is provided.
tests/cases/compiler/isolatedModulesPlainFile-CommonJS.ts(1,1): error TS1208: All files must be modules when the '--isolatedModules' flag is provided.
==== tests/cases/compiler/isolatedModulesPlainFile-CommonJS.ts (1 errors) ====
declare function run(a: number): void;
~~~~~~~
!!! error TS1208: Cannot compile namespaces when the '--isolatedModules' flag is provided.
!!! error TS1208: All files must be modules when the '--isolatedModules' flag is provided.
run(1);

View File

@ -1,9 +1,9 @@
tests/cases/compiler/isolatedModulesPlainFile-ES6.ts(1,1): error TS1208: Cannot compile namespaces when the '--isolatedModules' flag is provided.
tests/cases/compiler/isolatedModulesPlainFile-ES6.ts(1,1): error TS1208: All files must be modules when the '--isolatedModules' flag is provided.
==== tests/cases/compiler/isolatedModulesPlainFile-ES6.ts (1 errors) ====
declare function run(a: number): void;
~~~~~~~
!!! error TS1208: Cannot compile namespaces when the '--isolatedModules' flag is provided.
!!! error TS1208: All files must be modules when the '--isolatedModules' flag is provided.
run(1);

View File

@ -1,9 +1,9 @@
tests/cases/compiler/isolatedModulesPlainFile-System.ts(1,1): error TS1208: Cannot compile namespaces when the '--isolatedModules' flag is provided.
tests/cases/compiler/isolatedModulesPlainFile-System.ts(1,1): error TS1208: All files must be modules when the '--isolatedModules' flag is provided.
==== tests/cases/compiler/isolatedModulesPlainFile-System.ts (1 errors) ====
declare function run(a: number): void;
~~~~~~~
!!! error TS1208: Cannot compile namespaces when the '--isolatedModules' flag is provided.
!!! error TS1208: All files must be modules when the '--isolatedModules' flag is provided.
run(1);

View File

@ -1,9 +1,9 @@
tests/cases/compiler/isolatedModulesPlainFile-UMD.ts(1,1): error TS1208: Cannot compile namespaces when the '--isolatedModules' flag is provided.
tests/cases/compiler/isolatedModulesPlainFile-UMD.ts(1,1): error TS1208: All files must be modules when the '--isolatedModules' flag is provided.
==== tests/cases/compiler/isolatedModulesPlainFile-UMD.ts (1 errors) ====
declare function run(a: number): void;
~~~~~~~
!!! error TS1208: Cannot compile namespaces when the '--isolatedModules' flag is provided.
!!! error TS1208: All files must be modules when the '--isolatedModules' flag is provided.
run(1);

View File

@ -9,4 +9,5 @@ tests/cases/compiler/a.ts(1,5): error TS2403: Subsequent variable declarations m
==== tests/cases/compiler/a.ts (1 errors) ====
var x = 10; // Error reported so no declaration file generated?
~
!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'x' must be of type 'string', but here has type 'number'.
!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'x' must be of type 'string', but here has type 'number'.
!!! related TS6203 tests/cases/compiler/b.js:1:5: 'x' was also declared here.

Some files were not shown because too many files have changed in this diff Show More