Skip to content

Fix completions of optional properties in generic positions #33937

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
merged 18 commits into from
Oct 17, 2019
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
22 changes: 10 additions & 12 deletions src/compiler/checker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -174,12 +174,6 @@ namespace ts {
IsForSignatureHelp = 1 << 4, // Call resolution for purposes of signature help
}

const enum ContextFlags {
None = 0,
Signature = 1 << 0, // Obtaining contextual signature
NoConstraints = 1 << 1, // Don't obtain type variable constraints
}

const enum AccessFlags {
None = 0,
NoIndexSignatures = 1 << 0,
Expand Down Expand Up @@ -454,9 +448,9 @@ namespace ts {
},
getAugmentedPropertiesOfType,
getRootSymbols,
getContextualType: nodeIn => {
getContextualType: (nodeIn: Expression, contextFlags?: ContextFlags) => {
const node = getParseTreeNode(nodeIn, isExpression);
return node ? getContextualType(node) : undefined;
return node ? getContextualType(node, contextFlags) : undefined;
},
getContextualTypeForObjectLiteralElement: nodeIn => {
const node = getParseTreeNode(nodeIn, isObjectLiteralElementLike);
Expand Down Expand Up @@ -20887,19 +20881,23 @@ namespace ts {
}

// In a typed function call, an argument or substitution expression is contextually typed by the type of the corresponding parameter.
function getContextualTypeForArgument(callTarget: CallLikeExpression, arg: Expression): Type | undefined {
function getContextualTypeForArgument(callTarget: CallLikeExpression, arg: Expression, contextFlags?: ContextFlags): Type | undefined {
const args = getEffectiveCallArguments(callTarget);
const argIndex = args.indexOf(arg); // -1 for e.g. the expression of a CallExpression, or the tag of a TaggedTemplateExpression
return argIndex === -1 ? undefined : getContextualTypeForArgumentAtIndex(callTarget, argIndex);
return argIndex === -1 ? undefined : getContextualTypeForArgumentAtIndex(callTarget, argIndex, contextFlags);
}

function getContextualTypeForArgumentAtIndex(callTarget: CallLikeExpression, argIndex: number): Type {
function getContextualTypeForArgumentAtIndex(callTarget: CallLikeExpression, argIndex: number, contextFlags?: ContextFlags): Type {
// If we're already in the process of resolving the given signature, don't resolve again as
// that could cause infinite recursion. Instead, return anySignature.
const signature = getNodeLinks(callTarget).resolvedSignature === resolvingSignature ? resolvingSignature : getResolvedSignature(callTarget);
if (isJsxOpeningLikeElement(callTarget) && argIndex === 0) {
return getEffectiveFirstArgumentForJsxSignature(signature, callTarget);
}
if (contextFlags && contextFlags & ContextFlags.Completion && signature.target) {
const baseSignature = getBaseSignature(signature.target);
return intersectTypes(getTypeAtPosition(signature, argIndex), getTypeAtPosition(baseSignature, argIndex));
}
return getTypeAtPosition(signature, argIndex);
}

Expand Down Expand Up @@ -21291,7 +21289,7 @@ namespace ts {
}
/* falls through */
case SyntaxKind.NewExpression:
return getContextualTypeForArgument(<CallExpression | NewExpression>parent, node);
return getContextualTypeForArgument(<CallExpression | NewExpression>parent, node, contextFlags);
case SyntaxKind.TypeAssertionExpression:
case SyntaxKind.AsExpression:
return isConstTypeReference((<AssertionExpression>parent).type) ? undefined : getTypeFromTypeNode((<AssertionExpression>parent).type);
Expand Down
10 changes: 10 additions & 0 deletions src/compiler/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3365,8 +3365,10 @@ namespace ts {

getFullyQualifiedName(symbol: Symbol): string;
getAugmentedPropertiesOfType(type: Type): Symbol[];

getRootSymbols(symbol: Symbol): readonly Symbol[];
getContextualType(node: Expression): Type | undefined;
/* @internal */ getContextualType(node: Expression, contextFlags?: ContextFlags): Type | undefined; // eslint-disable-line @typescript-eslint/unified-signatures
/* @internal */ getContextualTypeForObjectLiteralElement(element: ObjectLiteralElementLike): Type | undefined;
/* @internal */ getContextualTypeForArgumentAtIndex(call: CallLikeExpression, argIndex: number): Type | undefined;
/* @internal */ getContextualTypeForJsxAttribute(attribute: JsxAttribute | JsxSpreadAttribute): Type | undefined;
Expand Down Expand Up @@ -3526,6 +3528,14 @@ namespace ts {
Subtype
}

/* @internal */
export const enum ContextFlags {
None = 0,
Signature = 1 << 0, // Obtaining contextual signature
NoConstraints = 1 << 1, // Don't obtain type variable constraints
Completion = 1 << 2, // Obtaining constraint type for completion
}

// NOTE: If modifying this enum, must modify `TypeFormatFlags` too!
export const enum NodeBuilderFlags {
None = 0,
Expand Down
4 changes: 3 additions & 1 deletion src/harness/fourslash.ts
Original file line number Diff line number Diff line change
Expand Up @@ -775,7 +775,9 @@ namespace FourSlash {
private verifyCompletionsWorker(options: FourSlashInterface.VerifyCompletionsOptions): void {
const actualCompletions = this.getCompletionListAtCaret({ ...options.preferences, triggerCharacter: options.triggerCharacter })!;
if (!actualCompletions) {
if (ts.hasProperty(options, "exact") && options.exact === undefined) return;
if (ts.hasProperty(options, "exact") && (options.exact === undefined || ts.isArray(options.exact) && !options.exact.length)) {
return;
}
this.raiseError(`No completions at position '${this.currentCaretPosition}'.`);
}

Expand Down
2 changes: 1 addition & 1 deletion src/services/completions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1760,7 +1760,7 @@ namespace ts.Completions {
let existingMembers: readonly Declaration[] | undefined;

if (objectLikeContainer.kind === SyntaxKind.ObjectLiteralExpression) {
const typeForObject = typeChecker.getContextualType(objectLikeContainer);
const typeForObject = typeChecker.getContextualType(objectLikeContainer, ContextFlags.Completion);
if (!typeForObject) return GlobalsSearch.Fail;
isNewIdentifierLocation = hasIndexSignature(typeForObject);
typeMembers = getPropertiesForObjectExpression(typeForObject, objectLikeContainer, typeChecker);
Expand Down
14 changes: 14 additions & 0 deletions tests/cases/fourslash/completionsGenericUnconstrained.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
/// <reference path="fourslash.ts" />
// @strict: true

////function f<T>(x: T) {
//// return x;
////}
////
////f({ /**/ });


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

//// declare function get<T, K extends keyof T>(obj: T, key: K): T[K];
//// get({ hello: 123, world: 456 }, "/**/");

verify.completions({
marker: "",
includes: ['hello', 'world']
});

19 changes: 19 additions & 0 deletions tests/cases/fourslash/completionsWithOptionalPropertiesGeneric.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
/// <reference path="fourslash.ts" />
// @strict: true

//// interface MyOptions {
//// hello?: boolean;
//// world?: boolean;
//// }
//// declare function bar<T extends MyOptions>(options?: Partial<T>): void;
//// bar({ hello, /*1*/ });

verify.completions({
marker: '1',
includes: [
{
sortText: completion.SortText.OptionalMember,
name: 'world'
},
]
})
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
/// <reference path="fourslash.ts" />
// @strict: true

//// interface Options {
//// someFunction?: () => string
//// anotherFunction?: () => string
//// }
////
//// export class Clazz<T extends Options> {
//// constructor(public a: T) {}
//// }
////
//// new Clazz({ /*1*/ })

verify.completions({
marker: '1',
includes: [
{
sortText: completion.SortText.OptionalMember,
name: 'someFunction'
},
{
sortText: completion.SortText.OptionalMember,
name: 'anotherFunction'
},
]
})
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
/// <reference path="fourslash.ts" />
// @strict: true

//// interface DeepOptions {
//// another?: boolean;
//// }
//// interface MyOptions {
//// hello?: boolean;
//// world?: boolean;
//// deep?: DeepOptions
//// }
//// declare function bar<T extends MyOptions>(options?: Partial<T>): void;
//// bar({ deep: {/*1*/} });

verify.completions({
marker: '1',
includes: [
{
sortText: completion.SortText.OptionalMember,
name: 'another'
},
]
})
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/// <reference path="fourslash.ts" />
// @strict: true

//// interface Foo {
//// a_a: boolean;
//// a_b: boolean;
//// a_c: boolean;
//// b_a: boolean;
//// }
//// function partialFoo<T extends Partial<Foo>>(t: T) {return t}
//// partialFoo({ /*1*/ });

verify.completions({
marker: '1',
includes: [
{
sortText: completion.SortText.OptionalMember,
name: 'a_a'
},
{
sortText: completion.SortText.OptionalMember,
name: 'a_b'
},
{
sortText: completion.SortText.OptionalMember,
name: 'a_c'
},
{
sortText: completion.SortText.OptionalMember,
name: 'b_a'
},
]
})
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
/// <reference path="fourslash.ts" />
// @strict: true

//// interface Foo {
//// a: boolean;
//// }
//// function partialFoo<T extends Partial<Foo>>(x: T, y: T) {return t}
//// partialFoo({ a: true, b: true }, { /*1*/ });

verify.completions({
marker: '1',
includes: [
{
sortText: completion.SortText.OptionalMember,
name: 'a'
},
{
sortText: completion.SortText.OptionalMember,
name: 'b'
}
]
})
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/// <reference path="fourslash.ts" />
// @strict: true

////interface Foo {
//// a: boolean;
////}
////function partialFoo<T extends Partial<Foo>>(x: T, y: T extends { b?: boolean } ? T & { c: true } : T) {
//// return x;
////}
////
////partialFoo({ a: true, b: true }, { /*1*/ });


verify.completions({
marker: '1',
includes: [
{
sortText: completion.SortText.OptionalMember,
name: 'a'
},
{
sortText: completion.SortText.OptionalMember,
name: 'b'
},
{
name: 'c'
}
]
})