Last active
June 8, 2024 09:56
-
-
Save johnsoncodehk/6b0932ac7ed3f192ad51474e04cb68b9 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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