Skip to content

Don't add completions from a discriminated union type when the discriminant doesn't match #24770

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

Merged
5 commits merged into from
Jul 4, 2018
Merged
Show file tree
Hide file tree
Changes from 3 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
19 changes: 19 additions & 0 deletions src/compiler/checker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,7 @@ namespace ts {
getDeclaredTypeOfSymbol,
getPropertiesOfType,
getPropertyOfType: (type, name) => getPropertyOfType(type, escapeLeadingUnderscores(name)),
getTypeOfPropertyOfType: (type, name) => getTypeOfPropertyOfType(type, escapeLeadingUnderscores(name)),
getIndexInfoOfType,
getSignaturesOfType,
getIndexTypeOfType,
Expand Down Expand Up @@ -291,6 +292,7 @@ namespace ts {
getNeverType: () => neverType,
isSymbolAccessible,
isArrayLikeType,
isTypeInvalidDueToUnionDiscriminant,
getAllPossiblePropertiesOfTypes,
getSuggestionForNonexistentProperty: (node, type) => getSuggestionForNonexistentProperty(node, type),
getSuggestionForNonexistentSymbol: (location, name, meaning) => getSuggestionForNonexistentSymbol(location, escapeLeadingUnderscores(name), meaning),
Expand Down Expand Up @@ -6746,6 +6748,19 @@ namespace ts {
getPropertiesOfObjectType(type);
}

function isTypeInvalidDueToUnionDiscriminant(contextualType: Type, obj: ObjectLiteralExpression): boolean {
return obj.properties.some(property => {
const name = property.name && getTextOfPropertyName(property.name);
const expected = name === undefined ? undefined : getTypeOfPropertyOfType(contextualType, name);
if (expected && typeIsLiteralType(expected)) {
const actual = getTypeOfNode(property);
// Apparently two literal types for the same literal are still not equal.
return !!actual && (!typeIsLiteralType(actual) || actual.value !== expected.value);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since you're in the checker now, I think you should probably use isIdenticalTo, or potentially isAssignableTo.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Alternatively, findMatchingDiscriminantType might be useful if you move all the filtering logic into the checker. Although it may be less flexible than you want, since it only selects exactly one type and not many (although, if you're trying to match normal discrimination behavior, that's where it is).

}
return false;
});
}

function getAllPossiblePropertiesOfTypes(types: ReadonlyArray<Type>): Symbol[] {
const unionType = getUnionType(types);
if (!(unionType.flags & TypeFlags.Union)) {
Expand Down Expand Up @@ -29011,4 +29026,8 @@ namespace ts {
export const IntrinsicClassAttributes = "IntrinsicClassAttributes" as __String;
// tslint:enable variable-name
}

function typeIsLiteralType(type: Type): type is LiteralType {
return !!(type.flags & TypeFlags.Literal);
}
}
6 changes: 6 additions & 0 deletions src/compiler/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2879,6 +2879,7 @@ namespace ts {
getDeclaredTypeOfSymbol(symbol: Symbol): Type;
getPropertiesOfType(type: Type): Symbol[];
getPropertyOfType(type: Type, propertyName: string): Symbol | undefined;
/* @internal */ getTypeOfPropertyOfType(type: Type, propertyName: string): Type | undefined;
getIndexInfoOfType(type: Type, kind: IndexKind): IndexInfo | undefined;
getSignaturesOfType(type: Type, kind: SignatureKind): ReadonlyArray<Signature>;
getIndexTypeOfType(type: Type, kind: IndexKind): Type | undefined;
Expand Down Expand Up @@ -3046,6 +3047,11 @@ namespace ts {
/* @internal */ getTypeCount(): number;

/* @internal */ isArrayLikeType(type: Type): boolean;
/**
* True if `contextualType` should not be considered for completions because
* e.g. it specifies `kind: "a"` and obj has `kind: "b"`.
*/
/* @internal */ isTypeInvalidDueToUnionDiscriminant(contextualType: Type, obj: ObjectLiteralExpression): boolean;
/**
* For a union, will include a property if it's defined in *any* of the member types.
* So for `{ a } | { b }`, this will include both `a` and `b`.
Expand Down
30 changes: 18 additions & 12 deletions src/services/completions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1105,7 +1105,7 @@ namespace ts.Completions {
// each individual type has. This is because we're going to add all identifiers
// anyways. So we might as well elevate the members that were at least part
// of the individual types to a higher status since we know what they are.
symbols.push(...getPropertiesForCompletion(type, typeChecker, /*isForAccess*/ true));
symbols.push(...getPropertiesForCompletion(type, typeChecker));
}
else {
for (const symbol of type.getApparentProperties()) {
Expand Down Expand Up @@ -1225,7 +1225,7 @@ namespace ts.Completions {
if (preferences.includeCompletionsWithInsertText && scopeNode.kind !== SyntaxKind.SourceFile) {
const thisType = typeChecker.tryGetThisTypeAt(scopeNode);
if (thisType) {
for (const symbol of getPropertiesForCompletion(thisType, typeChecker, /*isForAccess*/ true)) {
for (const symbol of getPropertiesForCompletion(thisType, typeChecker)) {
symbolToOriginInfoMap[getSymbolId(symbol)] = { type: "this-type" };
symbols.push(symbol);
}
Expand Down Expand Up @@ -1542,7 +1542,7 @@ namespace ts.Completions {
const typeForObject = typeChecker.getContextualType(objectLikeContainer);
if (!typeForObject) return GlobalsSearch.Fail;
isNewIdentifierLocation = hasIndexSignature(typeForObject);
typeMembers = getPropertiesForCompletion(typeForObject, typeChecker, /*isForAccess*/ false);
typeMembers = getPropertiesForObjectExpression(typeForObject, objectLikeContainer, typeChecker);
existingMembers = objectLikeContainer.properties;
}
else {
Expand Down Expand Up @@ -2163,19 +2163,25 @@ namespace ts.Completions {
return jsdoc && jsdoc.tags && (rangeContainsPosition(jsdoc, position) ? findLast(jsdoc.tags, tag => tag.pos < position) : undefined);
}

function getPropertiesForObjectExpression(contextualType: Type, obj: ObjectLiteralExpression, checker: TypeChecker): Symbol[] {
return contextualType.isUnion()
? checker.getAllPossiblePropertiesOfTypes(contextualType.types.filter(memberType =>
// If we're providing completions for an object literal, skip primitive, array-like, or callable types since those shouldn't be implemented by object literals.
!(memberType.flags & TypeFlags.Primitive ||
checker.isArrayLikeType(memberType) ||
typeHasCallOrConstructSignatures(memberType, checker) ||
checker.isTypeInvalidDueToUnionDiscriminant(memberType, obj))))
: contextualType.getApparentProperties();
}

/**
* Gets all properties on a type, but if that type is a union of several types,
* excludes array-like types or callable/constructable types.
*/
function getPropertiesForCompletion(type: Type, checker: TypeChecker, isForAccess: boolean): Symbol[] {
if (!(type.isUnion())) {
return Debug.assertEachDefined(type.getApparentProperties(), "getApparentProperties() should all be defined");
}

// If we're providing completions for an object literal, skip primitive, array-like, or callable types since those shouldn't be implemented by object literals.
const filteredTypes = isForAccess ? type.types : type.types.filter(memberType =>
!(memberType.flags & TypeFlags.Primitive || checker.isArrayLikeType(memberType) || typeHasCallOrConstructSignatures(memberType, checker)));
return Debug.assertEachDefined(checker.getAllPossiblePropertiesOfTypes(filteredTypes), "getAllPossiblePropertiesOfTypes() should all be defined");
function getPropertiesForCompletion(type: Type, checker: TypeChecker): Symbol[] {
return type.isUnion()
? Debug.assertEachDefined(checker.getAllPossiblePropertiesOfTypes(type.types), "getAllPossiblePropertiesOfTypes() should all be defined")
: Debug.assertEachDefined(type.getApparentProperties(), "getApparentProperties() should all be defined");
}

/**
Expand Down
7 changes: 7 additions & 0 deletions tests/cases/fourslash/completionsDiscriminatedUnion.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
/// <reference path="fourslash.ts" />

////interface A { kind: "a"; a: number; }
////interface B { kind: "b"; b: number; }
////const c: A | B = { kind: "a", /**/ };

verify.completions({ marker: "", exact: ["a"] });