簡體   English   中英

TypeScript編譯器API獲取導入名稱的類型

[英]TypeScript compiler API get type of imported names

請考慮以下import聲明。

import { a } from "moduleName"

我怎樣才能獲得聲明的類型的a 例如, ClassDeclarationFunctionDeclrationNamespace以及類或函數的類型名稱?

在上面的示例中, aImportSpecifier ,但是當我嘗試使用typeChecker.getSymbolAtLocationtypeChecker.getTypeAtLocation解析它時,我只獲得類型為anyIdentifier

您可以使用getTypeAtLocation獲取導入類型,然后使用type.getSymbol().getDeclarations()來獲取符號和聲明。

給出以下文件:

// module.ts
export class A {
}

export function F(){    
}

// sample.ts
import { A, F} from './module';

此代碼將輸出導入的聲明和完整類型名稱:

import * as ts from "typescript";

function compile(fileNames: string[], options: ts.CompilerOptions): void {
    let program = ts.createProgram(fileNames, options);
    let sample = program.getSourceFile("sample.ts");
    let checker = program.getTypeChecker();

    let list = sample.getChildAt(0) as ts.SyntaxList;
    let importStm = list.getChildAt(0);
    if (ts.isImportDeclaration(importStm)) { // get the declaration 
        let clauses = importStm.importClause;
        let namedImport = clauses.getChildAt(0); // get the named imports
        if (!ts.isNamedImports(namedImport)) return;
        for (let i = 0, n = namedImport.elements.length; i < n; i++) { // Iterate the named imports
            let imp = namedImport.elements[i];
            console.log(`Import: ${imp.getText()}`);
            // Get Type 
            let type = checker.getTypeAtLocation(imp);
            // Full name 
            console.log(`Name: ${checker.getFullyQualifiedName(type.getSymbol())}`);
            // Get the declarations (can be multiple), and print them 
            console.log(`Declarations: `)
            type.getSymbol().getDeclarations().forEach(d => console.log(d.getText()));
        }

    }
}

compile(["module.ts", "sample.ts"], {}); 

對於接口有一個復雜的問題,返回的類型是未知的,這是有意識地完成的,因為編譯器中的這個注釋告訴我們,它還建議一個解決方法:

// It only makes sense to get the type of a value symbol. If the result of resolving
// the alias is not a value, then it has no type. To get the type associated with a
// type symbol, call getDeclaredTypeOfSymbol.

所以對於我們需要使用的接口:

let symbol = checker.getSymbolAtLocation(imp.name)
// Get Type 
let type = checker.getDeclaredTypeOfSymbol(symbol);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM