cmudig / apigen

API Generator from TypeScript
BSD 3-Clause "New" or "Revised" License
3 stars 0 forks source link

Get Source File of a Type #22

Closed lan-lyu closed 1 year ago

lan-lyu commented 1 year ago

The goal is to generate

import {AutosizeType, AutoSizeParams} from 'vega-lite/src/spec/toplevel';

So wee need to know vega-lite/src/spec/toplevel is the source file of type AutosizeType and AutoSizeParams.

Refers to https://stackoverflow.com/questions/58653091/typescript-compiler-api-find-which-file-a-type-came-from, I can get the source file of the AST nodes(code), but I can't get such information from ts.Type or ts.TypeNode(code).

It's because ts.Type and ts.TypeNode doesn't have a symbol, so they can't call getSourceFile() function.

// get the source file of a type alias declaration
function findTypeDeclarationSourceFile(type: ts.TypeNode, checker: ts.TypeChecker): string | undefined {

    const symbol = checker.getSymbolAtLocation(type);  // return undefined

    if (symbol) {
        const declarations = symbol.getDeclarations();
        if (declarations) {
            const declaration = declarations[0];
            const sourceFile = declaration.getSourceFile();
            if (sourceFile) {
                return sourceFile.fileName;
            }
        }
    }

    return undefined;
}

Is there other ways I can get source file information from ts.TypeNode or ts.Type?

lan-lyu commented 1 year ago

Solve using this function https://github.com/cmudig/apigen/blob/3a6997d4a15fb333e3307600e7dacacd745bbe3d/explorationOnSpec/from-spec-clean-version.ts#L309