Skip to content

Instantly share code, notes, and snippets.

@mfbx9da4
Last active February 13, 2022 18:12
Show Gist options
  • Save mfbx9da4/68e6f134f77b03fbc8ea97f297f2a2ba to your computer and use it in GitHub Desktop.
Save mfbx9da4/68e6f134f77b03fbc8ea97f297f2a2ba to your computer and use it in GitHub Desktop.
/**
* The transformer signature is based on https://github.com/cevek/ttypescript#program
* Need to use https://github.com/microsoft/TypeScript/blob/bae0f508184280c59d2865a35efc63be362eacfa/src/compiler/factory/nodeFactory.ts
* The goal is to conver `a!.m()` to `if (!a) { throw new Error('Attempted to use nullish value "a"'} else { a.m() }`
* https://astexplorer.net/#/gist/9ec2af3e8c15fd2cde848941e14f566b/d9ddca954379374f98a4097d9bde4c346dac8567
*/
export default function (program) {
const checker = program.getTypeChecker()
return (context) => {
return (sourceFile) => {
const visitor = (node) => {
if (ts.isNonNullExpression(node)) {
console.log(node.expression)
const thrower = context.factory.createThrowStatement(
context.factory.createNewExpression(
context.factory.createStringLiteral('Error'),
undefined,
['Use of non null variable']
)
)
return context.factory.createIfStatement(
context.factory.createPrefixUnaryExpression(
ts.SyntaxKind.ExclamationToken,
context.factory.createIdentifier(node.expression.escapedText)
),
thrower
)
}
return ts.visitEachChild(node, visitor, context)
}
return ts.visitNode(sourceFile, visitor)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment