Improve string literal completions for property values when a partially-typed string fixes inference to a type parameter (#51770)

This commit is contained in:
Mateusz Burzyński 2022-12-20 22:08:55 +01:00 committed by GitHub
parent 5d8ef4bdcb
commit cf68a12d69
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 15 additions and 5 deletions

View File

@ -421,7 +421,7 @@ function getStringLiteralCompletionEntries(sourceFile: SourceFile, node: StringL
function fromContextualType(): StringLiteralCompletion {
// Get completion for string literal from string literal type
// i.e. var x: "hi" | "hello" = "/*completion position*/"
return { kind: StringLiteralCompletionKind.Types, types: getStringLiteralTypes(getContextualTypeFromParent(node, typeChecker)), isNewIdentifier: false };
return { kind: StringLiteralCompletionKind.Types, types: getStringLiteralTypes(getContextualTypeFromParent(node, typeChecker, ContextFlags.Completions)), isNewIdentifier: false };
}
}

View File

@ -29,6 +29,7 @@ import {
CompilerOptions,
ConditionalExpression,
contains,
ContextFlags,
createPrinter,
createRange,
createScanner,
@ -3270,21 +3271,21 @@ export function needsParentheses(expression: Expression): boolean {
}
/** @internal */
export function getContextualTypeFromParent(node: Expression, checker: TypeChecker): Type | undefined {
export function getContextualTypeFromParent(node: Expression, checker: TypeChecker, contextFlags?: ContextFlags): Type | undefined {
const { parent } = node;
switch (parent.kind) {
case SyntaxKind.NewExpression:
return checker.getContextualType(parent as NewExpression);
return checker.getContextualType(parent as NewExpression, contextFlags);
case SyntaxKind.BinaryExpression: {
const { left, operatorToken, right } = parent as BinaryExpression;
return isEqualityOperatorKind(operatorToken.kind)
? checker.getTypeAtLocation(node === right ? left : right)
: checker.getContextualType(node);
: checker.getContextualType(node, contextFlags);
}
case SyntaxKind.CaseClause:
return (parent as CaseClause).expression === node ? getSwitchedType(parent as CaseClause, checker) : undefined;
default:
return checker.getContextualType(node);
return checker.getContextualType(node, contextFlags);
}
}

View File

@ -0,0 +1,9 @@
/// <reference path="fourslash.ts" />
// @Filename: /a.tsx
//// declare function bar1<P extends "" | "bar" | "baz">(p: { type: P }): void;
////
//// bar1({ type: "/*ts*/" })
////
verify.completions({ marker: ["ts"], exact: ["", "bar", "baz"] });