feat(44720): allow renaming string literal in switch/case (#45084)

This commit is contained in:
Oleksandr T 2021-08-20 03:09:35 +03:00 committed by GitHub
parent 693c2d08c1
commit e00722f262
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 23 additions and 13 deletions

View File

@ -2003,13 +2003,13 @@ namespace ts.FindAllReferences {
}
function getReferencesForStringLiteral(node: StringLiteralLike, sourceFiles: readonly SourceFile[], checker: TypeChecker, cancellationToken: CancellationToken): SymbolAndEntries[] {
const type = getContextualTypeOrAncestorTypeNodeType(node, checker);
const type = getContextualTypeFromParentOrAncestorTypeNode(node, checker);
const references = flatMap(sourceFiles, sourceFile => {
cancellationToken.throwIfCancellationRequested();
return mapDefined(getPossibleSymbolReferenceNodes(sourceFile, node.text), ref => {
if (isStringLiteralLike(ref) && ref.text === node.text) {
if (type) {
const refType = getContextualTypeOrAncestorTypeNodeType(ref, checker);
const refType = getContextualTypeFromParentOrAncestorTypeNode(ref, checker);
if (type !== checker.getStringType() && type === refType) {
return nodeEntry(ref, EntryKind.StringLiteral);
}

View File

@ -15,7 +15,7 @@ namespace ts.Rename {
const symbol = typeChecker.getSymbolAtLocation(node);
if (!symbol) {
if (isStringLiteralLike(node)) {
const type = getContextualTypeOrAncestorTypeNodeType(node, typeChecker);
const type = getContextualTypeFromParentOrAncestorTypeNode(node, typeChecker);
if (type && ((type.flags & TypeFlags.StringLiteral) || (
(type.flags & TypeFlags.Union) && every((type as UnionType).types, type => !!(type.flags & TypeFlags.StringLiteral))
))) {

View File

@ -796,16 +796,9 @@ namespace ts {
return lastTypeNode;
}
export function getContextualTypeOrAncestorTypeNodeType(node: Expression, checker: TypeChecker) {
const contextualType = checker.getContextualType(node);
if (contextualType) {
return contextualType;
}
const parent = node.parent;
if (parent && isBinaryExpression(parent) && isEqualityOperatorKind(parent.operatorToken.kind)) {
return checker.getTypeAtLocation(node === parent.left ? parent.right : parent.left);
}
export function getContextualTypeFromParentOrAncestorTypeNode(node: Expression, checker: TypeChecker): Type | undefined {
const contextualType = getContextualTypeFromParent(node, checker);
if (contextualType) return contextualType;
const ancestorTypeNode = getAncestorTypeNode(node);
return ancestorTypeNode && checker.getTypeAtLocation(ancestorTypeNode);

View File

@ -0,0 +1,17 @@
/// <reference path='fourslash.ts' />
////type Foo = "[|a|]" | "b";
////
////class C {
//// p: Foo = "[|a|]";
//// m() {
//// switch (this.p) {
//// case "[|a|]":
//// return 1;
//// case "b":
//// return 2;
//// }
//// }
////}
verify.rangesWithSameTextAreRenameLocations("a");