Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Slightly improve missing property errors #28298

Merged
merged 8 commits into from
Nov 12, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 53 additions & 10 deletions src/compiler/checker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -431,6 +431,8 @@ namespace ts {
const numberOrBigIntType = getUnionType([numberType, bigintType]);

const emptyObjectType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined);
const emptyJsxObjectType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined);
emptyJsxObjectType.objectFlags |= ObjectFlags.JsxAttributes;

const emptyTypeLiteralSymbol = createSymbol(SymbolFlags.TypeLiteral, InternalSymbolName.Type);
emptyTypeLiteralSymbol.members = createSymbolTable();
Expand Down Expand Up @@ -11385,13 +11387,15 @@ namespace ts {
): boolean {

let errorInfo: DiagnosticMessageChain | undefined;
let relatedInfo: [DiagnosticRelatedInformation, ...DiagnosticRelatedInformation[]] | undefined;
let maybeKeys: string[];
let sourceStack: Type[];
let targetStack: Type[];
let maybeCount = 0;
let depth = 0;
let expandingFlags = ExpandingFlags.None;
let overflow = false;
let suppressNextError = false;

Debug.assert(relation !== identityRelation || !errorNode, "no error reporting in identity checking");

Expand Down Expand Up @@ -11422,16 +11426,29 @@ namespace ts {
}

const diag = createDiagnosticForNodeFromMessageChain(errorNode!, errorInfo, relatedInformation);
if (relatedInfo) {
addRelatedInfo(diag, ...relatedInfo);
}
if (errorOutputContainer) {
errorOutputContainer.error = diag;
}
diagnostics.add(diag); // TODO: GH#18217
}
return result !== Ternary.False;

function reportError(message: DiagnosticMessage, arg0?: string, arg1?: string, arg2?: string): void {
function reportError(message: DiagnosticMessage, arg0?: string | number, arg1?: string | number, arg2?: string | number, arg3?: string | number): void {
Debug.assert(!!errorNode);
errorInfo = chainDiagnosticMessages(errorInfo, message, arg0, arg1, arg2);
errorInfo = chainDiagnosticMessages(errorInfo, message, arg0, arg1, arg2, arg3);
}

function associateRelatedInfo(info: DiagnosticRelatedInformation) {
Debug.assert(!!errorInfo);
if (!relatedInfo) {
relatedInfo = [info];
}
else {
relatedInfo.push(info);
}
}

function reportRelationError(message: DiagnosticMessage | undefined, source: Type, target: Type) {
Expand Down Expand Up @@ -11639,13 +11656,15 @@ namespace ts {
}

if (!result && reportErrors) {
const maybeSuppress = suppressNextError;
suppressNextError = false;
if (source.flags & TypeFlags.Object && target.flags & TypeFlags.Primitive) {
tryElaborateErrorsForPrimitivesAndObjects(source, target);
}
else if (source.symbol && source.flags & TypeFlags.Object && globalObjectType === source) {
reportError(Diagnostics.The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead);
}
else if (getObjectFlags(source) & ObjectFlags.JsxAttributes && target.flags & TypeFlags.Intersection) {
else if (isComparingJsxAttributes && target.flags & TypeFlags.Intersection) {
const targetTypes = (target as IntersectionType).types;
const intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, errorNode);
const intrinsicClassAttributes = getJsxType(JsxNames.IntrinsicClassAttributes, errorNode);
Expand All @@ -11655,6 +11674,10 @@ namespace ts {
return result;
}
}
if (!headMessage && maybeSuppress) {
// Used by, eg, missing property checking to replace the top-level message with a more informative one
return result;
}
reportRelationError(headMessage, source, target);
}
return result;
Expand Down Expand Up @@ -12286,7 +12309,24 @@ namespace ts {
const unmatchedProperty = getUnmatchedProperty(source, target, requireOptionalProperties);
if (unmatchedProperty) {
if (reportErrors) {
reportError(Diagnostics.Property_0_is_missing_in_type_1, symbolToString(unmatchedProperty), typeToString(source));
const props = arrayFrom(getUnmatchedProperties(source, target, requireOptionalProperties));
if (!headMessage || (headMessage.code !== Diagnostics.Class_0_incorrectly_implements_interface_1.code &&
headMessage.code !== Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass.code)) {
suppressNextError = true; // Retain top-level error for interface implementing issues, otherwise omit it
}
if (props.length === 1) {
const propName = symbolToString(unmatchedProperty);
reportError(Diagnostics.Property_0_is_missing_in_type_1_but_required_in_type_2, propName, typeToString(source), typeToString(target));
if (length(unmatchedProperty.declarations)) {
associateRelatedInfo(createDiagnosticForNode(unmatchedProperty.declarations[0], Diagnostics._0_is_declared_here, propName));
}
}
else if (props.length > 5) { // arbitrary cutoff for too-long list form
reportError(Diagnostics.Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more, typeToString(source), typeToString(target), map(props.slice(0, 4), p => symbolToString(p)).join(", "), props.length - 4);
}
else {
reportError(Diagnostics.Type_0_is_missing_the_following_properties_from_type_1_Colon_2, typeToString(source), typeToString(target), map(props, p => symbolToString(p)).join(", "));
}
}
return Ternary.False;
}
Expand Down Expand Up @@ -13677,17 +13717,20 @@ namespace ts {
return getTypeFromInference(inference);
}

function getUnmatchedProperty(source: Type, target: Type, requireOptionalProperties: boolean) {
function* getUnmatchedProperties(source: Type, target: Type, requireOptionalProperties: boolean) {
const properties = target.flags & TypeFlags.Intersection ? getPropertiesOfUnionOrIntersectionType(<IntersectionType>target) : getPropertiesOfObjectType(target);
for (const targetProp of properties) {
if (requireOptionalProperties || !(targetProp.flags & SymbolFlags.Optional)) {
const sourceProp = getPropertyOfType(source, targetProp.escapedName);
if (!sourceProp) {
return targetProp;
yield targetProp;
}
}
}
return undefined;
}

function getUnmatchedProperty(source: Type, target: Type, requireOptionalProperties: boolean): Symbol | undefined {
return getUnmatchedProperties(source, target, requireOptionalProperties).next().value;
}

function tupleTypesDefinitelyUnrelated(source: TupleTypeReference, target: TupleTypeReference) {
Expand Down Expand Up @@ -17893,7 +17936,7 @@ namespace ts {
function createJsxAttributesTypeFromAttributesProperty(openingLikeElement: JsxOpeningLikeElement, checkMode: CheckMode | undefined) {
const attributes = openingLikeElement.attributes;
let attributesTable = createSymbolTable();
let spread: Type = emptyObjectType;
let spread: Type = emptyJsxObjectType;
let hasSpreadAnyType = false;
let typeToIntersect: Type | undefined;
let explicitlySpecifyChildrenAttribute = false;
Expand Down Expand Up @@ -17976,10 +18019,10 @@ namespace ts {
if (hasSpreadAnyType) {
return anyType;
}
if (typeToIntersect && spread !== emptyObjectType) {
if (typeToIntersect && spread !== emptyJsxObjectType) {
return getIntersectionType([typeToIntersect, spread]);
}
return typeToIntersect || (spread === emptyObjectType ? createJsxAttributesType() : spread);
return typeToIntersect || (spread === emptyJsxObjectType ? createJsxAttributesType() : spread);

/**
* Create anonymous type from given attributes symbol table.
Expand Down
6 changes: 3 additions & 3 deletions src/compiler/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1255,9 +1255,9 @@ namespace ts {
}

/** Shims `Array.from`. */
export function arrayFrom<T, U>(iterator: Iterator<T>, map: (t: T) => U): U[];
export function arrayFrom<T>(iterator: Iterator<T>): T[];
export function arrayFrom(iterator: Iterator<any>, map?: (t: any) => any): any[] {
export function arrayFrom<T, U>(iterator: Iterator<T> | IterableIterator<T>, map: (t: T) => U): U[];
export function arrayFrom<T>(iterator: Iterator<T> | IterableIterator<T>): T[];
export function arrayFrom(iterator: Iterator<any> | IterableIterator<any>, map?: (t: any) => any): any[] {
const result: any[] = [];
for (let { value, done } = iterator.next(); !done; { value, done } = iterator.next()) {
result.push(map ? map(value) : value);
Expand Down
12 changes: 12 additions & 0 deletions src/compiler/diagnosticMessages.json
Original file line number Diff line number Diff line change
Expand Up @@ -2513,6 +2513,18 @@
"category": "Message",
"code": 2738
},
"Type '{0}' is missing the following properties from type '{1}': {2}": {
"category": "Error",
"code": 2739
},
"Type '{0}' is missing the following properties from type '{1}': {2}, and {3} more.": {
"category": "Error",
"code": 2740
},
"Property '{0}' is missing in type '{1}' but required in type '{2}'.": {
"category": "Error",
"code": 2741
},

"Import declaration '{0}' is using private name '{1}'.": {
"category": "Error",
Expand Down
6 changes: 3 additions & 3 deletions src/compiler/utilities.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6914,8 +6914,8 @@ namespace ts {
getSourceMapSourceConstructor: () => <any>SourceMapSource,
};

export function formatStringFromArgs(text: string, args: ArrayLike<string>, baseIndex = 0): string {
return text.replace(/{(\d+)}/g, (_match, index: string) => Debug.assertDefined(args[+index + baseIndex]));
export function formatStringFromArgs(text: string, args: ArrayLike<string | number>, baseIndex = 0): string {
return text.replace(/{(\d+)}/g, (_match, index: string) => "" + Debug.assertDefined(args[+index + baseIndex]));
}

export let localizedDiagnosticMessages: MapLike<string> | undefined;
Expand Down Expand Up @@ -6994,7 +6994,7 @@ namespace ts {
};
}

export function chainDiagnosticMessages(details: DiagnosticMessageChain | undefined, message: DiagnosticMessage, ...args: (string | undefined)[]): DiagnosticMessageChain;
export function chainDiagnosticMessages(details: DiagnosticMessageChain | undefined, message: DiagnosticMessage, ...args: (string | number | undefined)[]): DiagnosticMessageChain;
export function chainDiagnosticMessages(details: DiagnosticMessageChain | undefined, message: DiagnosticMessage): DiagnosticMessageChain {
let text = getLocaleSpecificMessage(message);

Expand Down
3 changes: 3 additions & 0 deletions src/services/codefixes/fixAddMissingMember.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ namespace ts.codefix {
const errorCodes = [
Diagnostics.Property_0_does_not_exist_on_type_1.code,
Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code,
Diagnostics.Property_0_is_missing_in_type_1_but_required_in_type_2.code,
Diagnostics.Type_0_is_missing_the_following_properties_from_type_1_Colon_2.code,
Diagnostics.Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more.code
];
const fixId = "addMissingMember";
registerCodeFix({
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
tests/cases/conformance/expressions/contextualTyping/argumentExpressionContextualTyping.ts(16,5): error TS2345: Argument of type '(string | number | boolean)[]' is not assignable to parameter of type '[string, number, boolean]'.
Property '0' is missing in type '(string | number | boolean)[]'.
Type '(string | number | boolean)[]' is missing the following properties from type '[string, number, boolean]': 0, 1, 2
tests/cases/conformance/expressions/contextualTyping/argumentExpressionContextualTyping.ts(17,5): error TS2345: Argument of type '[string, number, true, ...(string | number | boolean)[]]' is not assignable to parameter of type '[string, number, boolean]'.
Types of property 'length' are incompatible.
Type 'number' is not assignable to type '3'.
tests/cases/conformance/expressions/contextualTyping/argumentExpressionContextualTyping.ts(18,5): error TS2345: Argument of type '{ x: (string | number)[]; y: { c: boolean; d: string; e: number; }; }' is not assignable to parameter of type '{ x: [any, any]; y: { c: any; d: any; e: any; }; }'.
Types of property 'x' are incompatible.
Type '(string | number)[]' is not assignable to type '[any, any]'.
Property '0' is missing in type '(string | number)[]'.
Type '(string | number)[]' is missing the following properties from type '[any, any]': 0, 1


==== tests/cases/conformance/expressions/contextualTyping/argumentExpressionContextualTyping.ts (3 errors) ====
Expand All @@ -28,7 +27,7 @@ tests/cases/conformance/expressions/contextualTyping/argumentExpressionContextua
baz(array); // Error
~~~~~
!!! error TS2345: Argument of type '(string | number | boolean)[]' is not assignable to parameter of type '[string, number, boolean]'.
!!! error TS2345: Property '0' is missing in type '(string | number | boolean)[]'.
!!! error TS2345: Type '(string | number | boolean)[]' is missing the following properties from type '[string, number, boolean]': 0, 1, 2
baz(["string", 1, true, ...array]); // Error
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
!!! error TS2345: Argument of type '[string, number, true, ...(string | number | boolean)[]]' is not assignable to parameter of type '[string, number, boolean]'.
Expand All @@ -38,5 +37,4 @@ tests/cases/conformance/expressions/contextualTyping/argumentExpressionContextua
~
!!! error TS2345: Argument of type '{ x: (string | number)[]; y: { c: boolean; d: string; e: number; }; }' is not assignable to parameter of type '{ x: [any, any]; y: { c: any; d: any; e: any; }; }'.
!!! error TS2345: Types of property 'x' are incompatible.
!!! error TS2345: Type '(string | number)[]' is not assignable to type '[any, any]'.
!!! error TS2345: Property '0' is missing in type '(string | number)[]'.
!!! error TS2345: Type '(string | number)[]' is missing the following properties from type '[any, any]': 0, 1
Loading