Closed
Description
TypeScript Version: 2.1.5
Recently in tslint
development there was the idea to create a discriminated union of all ts.Node
s 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