Ts-morph: Feature: node type narrowing equivalent of `switch(node.getKind())`?

Created on 26 Apr 2021  路  3Comments  路  Source: dsherret/ts-morph

Since we are in TypeScript, it would be nice to have a way to (logically) switch on node type in a way that narrows the type of the node variable in each branch of the switch.

In the bare bones Compiler API there is this whole family if ts.isXYZ() methods that return node is XYZ and can be used to narrow the type:

if (ts.isModuleBlock(node)) {
    // type of node is narrowed to ModuleBlock here
}

Can we somehow do the same with ts-morph? I can of course access the compilerNode property and use the Compiler API functions, but is it the right way?

question

Most helpful comment

You're looking for the Node export - https://ts-morph.com/utilities#type-guards

All 3 comments

See the Node.isX(node: X) static methods. Let me know if that鈥檚 what you were looking for.

You're looking for the Node export - https://ts-morph.com/utilities#type-guards

Thanks! New to this lib. Perhaps mention this in the docs near https://ts-morph.com/navigation/#traversal-control ?

Was this page helpful?
0 / 5 - 0 ratings