|
| 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 | + |
| 11 | + const node = getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); |
| 12 | + if (node.kind !== SyntaxKind.VariableDeclaration) return; |
| 13 | + |
| 14 | + const type = (node as VariableDeclaration).type; |
| 15 | + if (containsJSDocType(type)) { |
| 16 | + const tsType = getTypeFromJSDocType(type); |
| 17 | + return [{ |
| 18 | + description: formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Change_0_to_1), [getTextOfNode(type), tsType]), |
| 19 | + changes: [{ |
| 20 | + fileName: sourceFile.fileName, |
| 21 | + textChanges: [{ |
| 22 | + span: { start: type.getStart(), length: type.getWidth() }, |
| 23 | + newText: tsType |
| 24 | + }], |
| 25 | + }], |
| 26 | + }]; |
| 27 | + } |
| 28 | + } |
| 29 | + |
| 30 | + function containsJSDocType(type: TypeNode): boolean { |
| 31 | + switch (type.kind) { |
| 32 | + case SyntaxKind.JSDocUnknownType: |
| 33 | + case SyntaxKind.JSDocAllType: |
| 34 | + case SyntaxKind.JSDocVariadicType: |
| 35 | + return true; |
| 36 | + // TODO: Of course you can put JSDoc types inside normal types, like number?[] and so on |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + function getTypeFromJSDocType(type: TypeNode): string { |
| 41 | + switch (type.kind) { |
| 42 | + case SyntaxKind.JSDocUnknownType: |
| 43 | + case SyntaxKind.JSDocAllType: |
| 44 | + return "any"; |
| 45 | + case SyntaxKind.JSDocVariadicType: |
| 46 | + // this will surely work! |
| 47 | + return getTypeFromJSDocType((type as JSDocVariadicType).type) + "[]"; |
| 48 | + // TODO: Of course you can put JSDoc types inside normal types, like number?[] and so on |
| 49 | + } |
| 50 | + return getTextOfNode(type); |
| 51 | + } |
| 52 | +} |
0 commit comments