Skip to content

Instantly share code, notes, and snippets.

@johnsoncodehk
Last active June 8, 2024 09:56
Show Gist options
  • Save johnsoncodehk/6b0932ac7ed3f192ad51474e04cb68b9 to your computer and use it in GitHub Desktop.
Save johnsoncodehk/6b0932ac7ed3f192ad51474e04cb68b9 to your computer and use it in GitHub Desktop.
import type { Rule } from '@tsslint/config';
export function create(): Rule {
return ({ typescript: ts, sourceFile, languageService, reportWarning }) => {
ts.forEachChild(sourceFile, function walk(node) {
if (ts.isNonNullExpression(node)) {
const typeChecker = languageService.getProgram()!.getTypeChecker();
const type = typeChecker.getTypeAtLocation(node.expression);
if (
typeChecker.typeToString(type, undefined, ts.TypeFormatFlags.NoTruncation)
=== typeChecker.typeToString(type.getNonNullableType(), undefined, ts.TypeFormatFlags.NoTruncation)
) {
reportWarning(
`Unnecessary non-null assertion.`,
node.getStart(sourceFile),
node.getEnd()
).withFix(
'Remove unnecessary non-null assertion',
() => [{
fileName: sourceFile.fileName,
textChanges: [
{
newText: '',
span: {
start: node.expression.getEnd(),
length: node.getEnd() - node.expression.getEnd(),
},
}
],
}]
);
}
}
ts.forEachChild(node, walk);
});
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment