Last active
February 13, 2022 18:12
-
-
Save mfbx9da4/68e6f134f77b03fbc8ea97f297f2a2ba to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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