Skip to content

Improve autocomplete for union of tuples #58571

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

Open
wants to merge 20 commits into
base: main
Choose a base branch
from
Open
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
41 changes: 36 additions & 5 deletions src/compiler/checker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23832,7 +23832,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
findMostOverlappyType(source, target);
}

function discriminateTypeByDiscriminableItems(target: UnionType, discriminators: (readonly [() => Type, __String])[], related: (source: Type, target: Type) => boolean | Ternary) {
function discriminateTypeByDiscriminableItems(target: UnionType, discriminators: (readonly [() => Type, __String | number])[], related: (source: Type, target: Type) => boolean | Ternary) {
const types = target.types;
const include: Ternary[] = types.map(t => t.flags & TypeFlags.Primitive ? Ternary.False : Ternary.True);
for (const [getDiscriminatingType, propertyName] of discriminators) {
Expand All @@ -23842,7 +23842,9 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
let matched = false;
for (let i = 0; i < types.length; i++) {
if (include[i]) {
const targetType = getTypeOfPropertyOrIndexSignatureOfType(types[i], propertyName);
const targetType = typeof propertyName === "number"
? getContextualTypeForElementExpression(types[i], propertyName)
: getTypeOfPropertyOrIndexSignatureOfType(types[i], propertyName);
Copy link
Author

Choose a reason for hiding this comment

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

found that this was not working like I wanted with variadic tuple types, so for tuples im using getContextualTypeForElementExpression. Not sure if there's a better way to do this, also considered making this function an argument

if (targetType && related(getDiscriminatingType(), targetType)) {
matched = true;
}
Expand Down Expand Up @@ -31361,6 +31363,25 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
);
}

function discriminateContextualTypeByElements(node: ArrayLiteralExpression, contextualType: UnionType) {
const key = `D${getNodeId(node)},${getTypeId(contextualType)}`;
const cached = getCachedType(key);
if (cached) return cached;

// Create a discriminator for each element in the list
const discriminators = map(
Copy link
Author

Choose a reason for hiding this comment

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

In the object version of this function there is a check for isPossiblyDiscriminantValue. Is that necessary here?

Copy link
Contributor

Choose a reason for hiding this comment

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

I'd expect both functions to be very similar so I'd say - yes. if isPossiblyDiscriminantValue is needed there - it's also needed here.

node.elements,
(e, ndx) => [() => getContextFreeTypeOfExpression(e), ndx] as const,
);
const discriminatedType = discriminateTypeByDiscriminableItems(
contextualType,
discriminators,
Copy link
Contributor

Choose a reason for hiding this comment

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

food for thought: length should also be treated as a potential discriminant but it probably should be ignored when requesting the contextual type for completions. You could try to use ContextFlags.Completions for that or you might have to introduce a new context flag for this purpose, smth like ContextFlags.NoTupleBounds.

Copy link
Author

Choose a reason for hiding this comment

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

removed the length check in getMatchingUnionConstituentForArrayLiteral so not sure if this is still relevant

Copy link
Contributor

Choose a reason for hiding this comment

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

it's relevant because this arg could contextually be typed as number

const tup: [(arg: number) => void] | [(arg: string) => void, number] = [
  (arg) => {},
];

isTypeAssignableTo,
);

return setCachedType(key, discriminatedType);
}

// Return the contextual type for a given expression node. During overload resolution, a contextual type may temporarily
// be "pushed" onto a node using the contextualType property.
function getApparentTypeOfContextualType(node: Expression | MethodDeclaration, contextFlags: ContextFlags | undefined): Type | undefined {
Expand All @@ -31378,9 +31399,19 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
t => getObjectFlags(t) & ObjectFlags.Mapped ? t : getApparentType(t),
/*noReductions*/ true,
);
return apparentType.flags & TypeFlags.Union && isObjectLiteralExpression(node) ? discriminateContextualTypeByObjectMembers(node, apparentType as UnionType) :
apparentType.flags & TypeFlags.Union && isJsxAttributes(node) ? discriminateContextualTypeByJSXAttributes(node, apparentType as UnionType) :
apparentType;
const isUnion = apparentType.flags & TypeFlags.Union;
if (isUnion && isObjectLiteralExpression(node)) {
return discriminateContextualTypeByObjectMembers(node, apparentType as UnionType);
}
else if (isUnion && isJsxAttributes(node)) {
return discriminateContextualTypeByJSXAttributes(node, apparentType as UnionType);
}
else if (contextFlags && contextFlags & ContextFlags.Completions && isUnion && isArrayLiteralExpression(node)) {
return discriminateContextualTypeByElements(node, instantiatedType as UnionType);
}
else {
return apparentType;
}
}
}

Expand Down
11 changes: 8 additions & 3 deletions src/services/stringCompletions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -479,7 +479,8 @@ function getStringLiteralCompletionEntries(sourceFile: SourceFile, node: StringL
function fromContextualType(contextFlags: ContextFlags = ContextFlags.Completions): StringLiteralCompletionsFromTypes | undefined {
// Get completion for string literal from string literal type
// i.e. var x: "hi" | "hello" = "/*completion position*/"
const types = getStringLiteralTypes(getContextualTypeFromParent(node, typeChecker, contextFlags));
const contextualType = getContextualTypeFromParent(node, typeChecker, contextFlags);
const types = getStringLiteralTypes(contextualType);
if (!types.length) {
return;
}
Expand Down Expand Up @@ -552,8 +553,12 @@ function stringLiteralCompletionsForObjectLiteral(checker: TypeChecker, objectLi
function getStringLiteralTypes(type: Type | undefined, uniques = new Map<string, true>()): readonly StringLiteralType[] {
if (!type) return emptyArray;
type = skipConstraint(type);
return type.isUnion() ? flatMap(type.types, t => getStringLiteralTypes(t, uniques)) :
type.isStringLiteral() && !(type.flags & TypeFlags.EnumLiteral) && addToSeen(uniques, type.value) ? [type] : emptyArray;
if (type.isUnion()) {
return flatMap(type.types, t => getStringLiteralTypes(t, uniques));
}
else {
return type.isStringLiteral() && !(type.flags & TypeFlags.EnumLiteral) && addToSeen(uniques, type.value) ? [type] : emptyArray;
}
}

interface NameAndKind {
Expand Down
5 changes: 5 additions & 0 deletions tests/cases/fourslash/completionsTuple2.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
/// <reference path="fourslash.ts" />

////declare const x: ["a", "b"] = ["x", "/**/"]

verify.completions({ marker: "", exact: ["b"] });
5 changes: 5 additions & 0 deletions tests/cases/fourslash/completionsTuple3.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
/// <reference path="fourslash.ts" />

////declare const x: ["a", ["b"], "x", ["y"]] = ["a", ["/**/"]]

verify.completions({ marker: "", exact: ["b"] });
6 changes: 6 additions & 0 deletions tests/cases/fourslash/completionsTupleUnion1.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
/// <reference path="fourslash.ts" />

////declare const a: "a";
////declare const x: ['a', 'b'] | ['a', 'c'] | ['d', 'e'] = [a, "/**/"];

verify.completions({ marker: "", exact: ["b", "c"] });
4 changes: 4 additions & 0 deletions tests/cases/fourslash/completionsTupleUnion10.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
/// <reference path="fourslash.ts" />
////declare const x: ['a', 'b'] | { '0': 'x', '1': 'y' } | { '1': 'z' } = ['x', '/**/'];

verify.completions({ marker: "", exact: ["y"] });
5 changes: 5 additions & 0 deletions tests/cases/fourslash/completionsTupleUnion11.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
/// <reference path="fourslash.ts" />
////type ABC = "a" | "b" | "c";
////declare const x: ['abc', ...ABC[]] | ['abc', 'abc', "f"] = ['abc', 'abc', '/**/'];

verify.completions({ marker: "", exact: ["f"] });
4 changes: 4 additions & 0 deletions tests/cases/fourslash/completionsTupleUnion12.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
/// <reference path="fourslash.ts" />
////declare const x: [(arg: number) => void, "num"] | [(arg: string) => void, "str"] | [(arg: boolean) => boolean, "val"] = [() => {}, '/**/'];

verify.completions({ marker: "", exact: ["num", "str"] });
4 changes: 4 additions & 0 deletions tests/cases/fourslash/completionsTupleUnion13.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
/// <reference path="fourslash.ts" />
////declare const x: [(arg: number) => void, "num"] | [(arg: string) => void, "str"] | [(arg: number) => number, "num2"] = [(x: number) => {}, '/**/'];

verify.completions({ marker: "", exact: ["num"] });
6 changes: 6 additions & 0 deletions tests/cases/fourslash/completionsTupleUnion2.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
/// <reference path="fourslash.ts" />

////declare const a: "a";
////declare const x: [{ t: "a" }, "b"] | [{ t: "b" }, "c"] = [{ t: a }, "/**/"]

verify.completions({ marker: "", exact: ["b"] });
6 changes: 6 additions & 0 deletions tests/cases/fourslash/completionsTupleUnion3.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
/// <reference path="fourslash.ts" />

////declare const a: "a";
////declare const x: ['a', 'b', 'f'] | ['a', 'b'] = [a, 'b', "/**/"];

verify.completions({ marker: "", exact: ["f"] });
5 changes: 5 additions & 0 deletions tests/cases/fourslash/completionsTupleUnion4.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
/// <reference path="fourslash.ts" />

////declare const x: ['a', 'b', 'f', 'g'] | ['a', 'b'] = ["a", 'b', 'f', "/**/"];

verify.completions({ marker: "", exact: ["g"] });
5 changes: 5 additions & 0 deletions tests/cases/fourslash/completionsTupleUnion5.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
/// <reference path="fourslash.ts" />

////declare const x: ['a', 'b'] | ['a', 'c'] = ['b', "/**/"];

verify.completions({ marker: "", exact: ["b", "c"] });
5 changes: 5 additions & 0 deletions tests/cases/fourslash/completionsTupleUnion6.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
/// <reference path="fourslash.ts" />

////declare const x: ['a', 'v1'] | ['b', 'v2'] = ['b', "v/**/"];

verify.completions({ marker: "", exact: ["v2"] });
6 changes: 6 additions & 0 deletions tests/cases/fourslash/completionsTupleUnion7.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
/// <reference path="fourslash.ts" />
////type ABC = "a" | "b" | "c";
////type XYZ = "x" | "y" | "z";
////declare const x: ['abc', ABC] | ['xyz', ...XYZ[]] = ['xyz', 'x', 'x', 'x', 'x', '/**/'];

verify.completions({ marker: "", exact: ["x", "y", "z"] });
6 changes: 6 additions & 0 deletions tests/cases/fourslash/completionsTupleUnion8.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
/// <reference path="fourslash.ts" />
////type ABC = "a" | "b" | "c";
////type XYZ = "x" | "y" | "z";
////declare const x: ['abc', ...ABC[]] | ['xyz', ...XYZ[]] = ['abc', 'a', 'b', 'c', 'a', '/**/'];

verify.completions({ marker: "", exact: ["a", "b", "c"] });
5 changes: 5 additions & 0 deletions tests/cases/fourslash/completionsTupleUnion9.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
/// <reference path="fourslash.ts" />
////type ABC = "a" | "b" | "c";
////declare const x: ['abc', ...ABC[]] | ['abc', "a", "f"] = ['abc', 'a', '/**/'];

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