|
| 1 | +/* @internal */ |
| 2 | +namespace ts.codefix { |
| 3 | + registerCodeFix({ |
| 4 | + errorCodes: [Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments.code], |
| 5 | + getCodeActions: getActionsForJSDocTypes |
| 6 | + }); |
| 7 | + |
| 8 | + function getActionsForJSDocTypes(context: CodeFixContext): CodeAction[] | undefined { |
| 9 | + const sourceFile = context.sourceFile; |
| 10 | + const node = getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); |
| 11 | + const decl = ts.findAncestor(node, n => n.kind === SyntaxKind.VariableDeclaration); |
| 12 | + if (!decl) return; |
| 13 | + const checker = context.program.getTypeChecker(); |
| 14 | + |
| 15 | + const jsdocType = (decl as VariableDeclaration).type; |
| 16 | + const original = getTextOfNode(jsdocType); |
| 17 | + const type = checker.getTypeFromTypeNode(jsdocType); |
| 18 | + const actions = [createAction(jsdocType, sourceFile.fileName, original, checker.typeToString(type, /*enclosingDeclaration*/ undefined, TypeFormatFlags.NoTruncation))]; |
| 19 | + if (jsdocType.kind === SyntaxKind.JSDocNullableType) { |
| 20 | + // for nullable types, suggest the flow-compatible `T | null | undefined` |
| 21 | + // in addition to the jsdoc/closure-compatible `T | null` |
| 22 | + const replacementWithUndefined = checker.typeToString(checker.getNullableType(type, TypeFlags.Undefined), /*enclosingDeclaration*/ undefined, TypeFormatFlags.NoTruncation); |
| 23 | + actions.push(createAction(jsdocType, sourceFile.fileName, original, replacementWithUndefined)); |
| 24 | + } |
| 25 | + return actions; |
| 26 | + } |
| 27 | + |
| 28 | + function createAction(declaration: TypeNode, fileName: string, original: string, replacement: string): CodeAction { |
| 29 | + return { |
| 30 | + description: formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Change_0_to_1), [original, replacement]), |
| 31 | + changes: [{ |
| 32 | + fileName, |
| 33 | + textChanges: [{ |
| 34 | + span: { start: declaration.getStart(), length: declaration.getWidth() }, |
| 35 | + newText: replacement |
| 36 | + }] |
| 37 | + }], |
| 38 | + }; |
| 39 | + } |
| 40 | +} |
0 commit comments