|
| 1 | +import { findChildContainingExactPosition } from '../utils' |
| 2 | +import { sharedCompletionContext } from './sharedContext' |
| 3 | + |
| 4 | +const getCastedTypeCompletionEntry = (typeChecker: ts.TypeChecker, node: ts.Expression) => { |
| 5 | + const typeAtLocation = typeChecker.getTypeAtLocation(node) |
| 6 | + const type = typeChecker.typeToString(typeAtLocation) |
| 7 | + const widenType = typeChecker.typeToString(typeChecker.getBaseTypeOfLiteralType(typeAtLocation)) |
| 8 | + |
| 9 | + return { |
| 10 | + kind: ts.ScriptElementKind.unknown, |
| 11 | + name: type === widenType ? type : widenType, |
| 12 | + sortText: '!', |
| 13 | + } |
| 14 | +} |
| 15 | + |
| 16 | +export default () => { |
| 17 | + const typeChecker = sharedCompletionContext.program.getTypeChecker() |
| 18 | + const { position, fullText, prior } = sharedCompletionContext |
| 19 | + |
| 20 | + // as completions |
| 21 | + if (fullText.slice(0, position - 1).endsWith('as')) { |
| 22 | + const node = findChildContainingExactPosition(sharedCompletionContext.sourceFile, position - 2) |
| 23 | + if (!node || !ts.isAsExpression(node)) return |
| 24 | + const entry = getCastedTypeCompletionEntry(typeChecker, node.expression) |
| 25 | + prior.entries.push(entry) |
| 26 | + return |
| 27 | + } |
| 28 | + |
| 29 | + // jsdoc typecast completions |
| 30 | + const node = findChildContainingExactPosition(sharedCompletionContext.sourceFile, position) |
| 31 | + if (!node) return |
| 32 | + let typeCastedNode: ts.ParenthesizedExpression | undefined |
| 33 | + node.forEachChild(node => { |
| 34 | + if (ts.isParenthesizedExpression(node) && ts.getJSDocTypeTag(node)) typeCastedNode = node |
| 35 | + }) |
| 36 | + |
| 37 | + if (!typeCastedNode) return |
| 38 | + const entry = getCastedTypeCompletionEntry(typeChecker, typeCastedNode.expression) |
| 39 | + prior.entries.push(entry) |
| 40 | +} |
0 commit comments