Skip to content

Provide a disciminated union of all available Node types #13634

Closed
@ajafff

Description

@ajafff

TypeScript Version: 2.1.5

Recently in tslint development there was the idea to create a discriminated union of all ts.Nodes available in the AST. That would make it easier to switch on Node.kind and avoid the need of type assertions. It would also simplify some of TypeScript's own code like forEachChild in parser.ts.

Before we start to create and maintain such a union ourselves, the question is if typescript can provide anything for this use case? Given there are already unions for things like BlockLike, CallLikeExpression, etc., would it be possible to have more of them, maybe even auto generated?

Unfortunately that would ultimately result in the demand for more unions for Expression, Statement, ...

Code

ts.forEachChild(someNode, visitNode);
function visitNode(node: ts.Node) {
  switch (node.kind) {
    case ts.SyntaxKind.Identifier:
      doStuff((node as ts.Identifier).text);
    case ts.SyntaxKind.PropertyAssignment:
      if ((node as ts.PropertyAssignment).initializer.kind === ts.SyntaxKind.Identifier)
        doStuff(((node as ts.PropertyAssignment).initializer as ts.Identifier).text);
     // ... to be continued
  }
}

Expected behavior:

ts.forEachChild(someNode, visitNode);
function visitNode(node: ts.AllNodes) { // discriminated union of all subtypes of ts.Node
  switch (node.kind) {
    case ts.SyntaxKind.Identifier:
      doStuff(node.text); // type can be inferred
    case ts.SyntaxKind.PropertyAssignment:
      if (node.initializer.kind === ts.SyntaxKind.Identifier) // node is inferred as ts.PropertyAssignment
        doStuff(node.initializer.text); // node.initializer could be inferred to be ts.Identifier, would require another union for all subtypes of ts.Expression
  }
}

//cc @nchen63

Metadata

Metadata

Assignees

No one assigned

    Labels

    DeclinedThe issue was declined as something which matches the TypeScript visionInfrastructureIssue relates to TypeScript team infrastructureSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions