Add codefix for jsdoc types in Typescript

It only handles a few simple types right now, but the skeleton is there.
This commit is contained in:
Nathan Shively-Sanders
2017-07-14 16:27:36 -07:00
parent a3a6862d43
commit efdba54deb
3 changed files with 55 additions and 2 deletions

View File

@@ -32,7 +32,7 @@ namespace ts.codefix {
}
}
// If all fails, add an extra new line immediatlly before the error span.
// If all fails, add an extra new line immediately before the error span.
return {
span: { start: position, length: 0 },
newText: `${position === startPosition ? "" : newLineCharacter}// @ts-ignore${newLineCharacter}`
@@ -67,4 +67,4 @@ namespace ts.codefix {
}]
}];
}
}
}

View File

@@ -0,0 +1,52 @@
/* @internal */
namespace ts.codefix {
registerCodeFix({
errorCodes: [Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments.code],
getCodeActions: getActionsForJSDocTypes
});
function getActionsForJSDocTypes(context: CodeFixContext): CodeAction[] | undefined {
const sourceFile = context.sourceFile;
const node = getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false);
if (node.kind !== SyntaxKind.VariableDeclaration) return;
const type = (node as VariableDeclaration).type;
if (containsJSDocType(type)) {
const tsType = getTypeFromJSDocType(type);
return [{
description: formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Change_0_to_1), [getTextOfNode(type), tsType]),
changes: [{
fileName: sourceFile.fileName,
textChanges: [{
span: { start: type.getStart(), length: type.getWidth() },
newText: tsType
}],
}],
}];
}
}
function containsJSDocType(type: TypeNode): boolean {
switch (type.kind) {
case SyntaxKind.JSDocUnknownType:
case SyntaxKind.JSDocAllType:
case SyntaxKind.JSDocVariadicType:
return true;
// TODO: Of course you can put JSDoc types inside normal types, like number?[] and so on
}
}
function getTypeFromJSDocType(type: TypeNode): string {
switch (type.kind) {
case SyntaxKind.JSDocUnknownType:
case SyntaxKind.JSDocAllType:
return "any";
case SyntaxKind.JSDocVariadicType:
// this will surely work!
return getTypeFromJSDocType((type as JSDocVariadicType).type) + "[]";
// TODO: Of course you can put JSDoc types inside normal types, like number?[] and so on
}
return getTextOfNode(type);
}
}

View File

@@ -7,6 +7,7 @@
/// <reference path="fixExtendsInterfaceBecomesImplements.ts" />
/// <reference path="fixForgottenThisPropertyAccess.ts" />
/// <reference path='fixUnusedIdentifier.ts' />
/// <reference path='fixJSDocTypes.ts' />
/// <reference path='importFixes.ts' />
/// <reference path='disableJsDiagnostics.ts' />
/// <reference path='helpers.ts' />