Skip to content

Commit

Permalink
Call widening functions on the correct type when adding satisfies to …
Browse files Browse the repository at this point in the history
…expressions

Widening of types only work on types from variable declaration, so when
getWidenedLiteralType is being called on expressions the compiler wouldn't
widen it. So call getWidenedLiteralType on the type of variables instead on
those cases.
  • Loading branch information
h-joo committed Apr 26, 2024
1 parent 5704f4e commit cb45ffe
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 3 deletions.
9 changes: 7 additions & 2 deletions src/services/codefixes/fixMissingTypeAnnotationOnExports.ts
Expand Up @@ -375,7 +375,7 @@ function withContext<T>(

if (!(isExpressionTarget || isShorthandPropertyAssignmentTarget)) return undefined;

const { typeNode, mutatedTarget } = inferType(targetNode);
const { typeNode, mutatedTarget } = inferType(targetNode, type);
if (!typeNode || mutatedTarget) return undefined;

if (isShorthandPropertyAssignmentTarget) {
Expand Down Expand Up @@ -921,7 +921,7 @@ function withContext<T>(
mutatedTarget: boolean;
}

function inferType(node: Node): InferenceResult {
function inferType(node: Node, variableType?: Type | undefined): InferenceResult {
if (typePrintMode === TypePrintMode.RELATIVE) {
return relativeType(node);
}
Expand All @@ -934,6 +934,11 @@ function withContext<T>(
}

if (typePrintMode === TypePrintMode.WIDENED) {
if (variableType) {
type = variableType;
}
// Widening of types can happen on union of type literals on
// declaration emit so we query it.
const widenedType = typeChecker.getWidenedLiteralType(type);
if (typeChecker.isTypeAssignableTo(widenedType, type)) {
return emptyInferenceResult;
Expand Down
Expand Up @@ -22,11 +22,14 @@ verify.codeFixAvailable([
},
{
"description": "Add satisfies and an inline type assertion with 'typeof A | typeof B'"
},
{
"description": "Add satisfies and an inline type assertion with 'string'"
}
])
verify.codeFix({
description: "Add satisfies and an inline type assertion with 'typeof A | typeof B'" ,
index: 3,
index: 4,
newFileContent:
`const A = "A"
const B = "B"
Expand Down

0 comments on commit cb45ffe

Please sign in to comment.