Skip to content
This repository was archived by the owner on Jan 19, 2019. It is now read-only.
This repository was archived by the owner on Jan 19, 2019. It is now read-only.

How to hande declare var stataments? #185

Closed
@Pajn

Description

@Pajn

Another thing I run in to when playing with prettier/prettier/issues/13 is declare var statements.

Currently prettier transforms

declare var x: any;

to

var x: any;

(the declare modifier is gone)

If we want to follow the Flow AST typescript-eslint-parser must parse it into an DeclareVariable node.
The DeclareVariable node is basically a VariableDeclarator directly (which otherwise are elements in the declarations array of VariableDeclaration).
The TS AST does instead set the DeclareKeyword as a modifier on the SyntaxKind.VariableStatement node (which usually becomes a VariableDeclaration).

A quick fix is this patch

diff --git a/lib/ast-converter.js b/lib/ast-converter.js
index 48ba730..33f025f 100644
--- a/lib/ast-converter.js
+++ b/lib/ast-converter.js
@@ -943,6 +943,24 @@ module.exports = function(ast, extra) {
                 break;

             case SyntaxKind.VariableStatement:
+                if (node.modifiers && node.modifiers.length) {
+                    var isDeclareVariable = node.modifiers.some(function(modifier) {
+                        return modifier.kind === ts.SyntaxKind.DeclareKeyword;
+                    });
+                    if (isDeclareVariable) {
+                        assign(result, {
+                            type: "DeclareVariable",
+                            id: convertChild(node.declarationList.declarations[0]),
+                            init: convertChild(node.initializer)
+                        });
+
+                        if (node.type) {
+                            result.id.typeAnnotation = convertTypeAnnotation(node.type);
+                        }
+                        break;
+                    }
+                }
+
                 assign(result, {
                     type: "VariableDeclaration",
                     declarations: node.declarationList.declarations.map(convertChild),

however it breaks quite soon as TypeScript seem to allow multiple declarations in the same statement like so:

declare var x: any, y: any;

So it seems like a new node type or a custom property on the variable declaration might be needed.

This probably isn't the highest priority issue for typescript support in prettier, I just happened to get one of those in my initial pull of test files. But I still wanted to submit an issue so it isn't forgotten :)

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions