|
| 1 | +//@ts-check |
| 2 | +import ts from 'typescript/lib/tsserverlibrary' |
| 3 | +import { createLanguageService } from './typescript/src/dummyLanguageService' |
| 4 | + |
| 5 | +let testString = 'const a: {/** @default test */a: 5} | {b: 6, /** yes */a: 9} = null as any;\nif ("||" in a) {}' |
| 6 | +const replacement = '||' |
| 7 | +const pos = testString.indexOf(replacement) |
| 8 | +testString = testString.slice(0, pos) + testString.slice(pos + replacement.length) |
| 9 | +const filePath = '/test.ts' |
| 10 | +const languageService = createLanguageService({ |
| 11 | + [filePath]: testString, |
| 12 | +}) |
| 13 | + |
| 14 | +const program = languageService.getProgram() |
| 15 | +const sourceFile = program?.getSourceFile(filePath) |
| 16 | +if (!program || !sourceFile) throw new Error('No source file') |
| 17 | + |
| 18 | +const typeChecker = program.getTypeChecker() |
| 19 | +const node = findChildContainingPosition(ts, sourceFile, pos) |
| 20 | +if (!node) throw new Error('No node') |
| 21 | +const type = typeChecker.getTypeAtLocation(node) |
| 22 | + |
| 23 | +// explore: |
| 24 | + |
| 25 | +console.log(typeChecker.typeToString(type)) |
| 26 | + |
| 27 | +function findChildContainingPosition( |
| 28 | + typescript: typeof import('typescript/lib/tsserverlibrary'), |
| 29 | + sourceFile: ts.SourceFile, |
| 30 | + position: number, |
| 31 | +): ts.Node | undefined { |
| 32 | + function find(node: ts.Node): ts.Node | undefined { |
| 33 | + if (position >= node.getStart() && position < node.getEnd()) return typescript.forEachChild(node, find) || node |
| 34 | + |
| 35 | + return |
| 36 | + } |
| 37 | + return find(sourceFile) |
| 38 | +} |
0 commit comments