ค้นหาเว็บไซต์

ดึงประเภทค่าที่ส่งกลับที่คาดเดาได้ด้วย API ของ TypeScript


ฉันสามารถโต้ตอบกับ API ของคอมไพเลอร์ TypeScript เพื่อคอมไพล์ *.ts เป็น *.js

import * as ts from "typescript";

const source = "function foo(xs: Array<number>) { let total=0; for (const x of xs) { total += x; } return total; }";

let result = ts.transpileModule(source, { compilerOptions: { module: ts.ModuleKind.CommonJS }});

console.log(JSON.stringify(result, null, 4));

มีวิธีใดบ้างที่ฉันจะสามารถได้ประเภทค่าที่ส่งกลับที่ถูกสรุปของ foo?

คำตอบ #1

วิธีหนึ่งในการหาชนิดของค่าที่ส่งกลับคือการใช้ตัวตรวจชนิดของ API ของคอมไพเลอร์:

  1. อันดับแรกคุณจะต้องสร้าง AST จากซอร์สโค้ดของคุณโดยใช้ createProgram
  2. รับตัวตรวจสอบประเภทสำหรับโปรแกรมนั้นด้วย getTypeChecker
  3. ค้นหาโหนด AST ของการประกาศฟังก์ชันนั้น
  4. แยกลายเซ็นของคำประกาศนั้นโดยใช้ getSignatureFromDeclaration
  5. แยกประเภทการคืนค่าของลายเซ็นโดยใช้ getReturnType (นี่จะได้วัตถุ ts.Type)

อาจจะมีวิธีที่ง่ายกว่าในการได้สิ่งที่คุณต้องการ แต่วิธีนี้ใช้ได้ผลสำหรับฉัน

ตัวอย่างเช่น ถ้าฟังก์ชันของคุณอยู่ในไฟล์ fun.ts:

const program = ts.createProgram(['fun.ts'])
const checker = program.getTypeChecker()
const sourceFile = program.getSourceFiles().filter(sf => !sf.isDeclarationFile)[0] // to filter all unwanted declaration files
const decl = sourceFile.statements[0] as ts.FunctionDeclaration
const retType = checker.getSignatureFromDeclaration(decl)!.getReturnType()

คำตอบ #2

ตามคำตอบของ @AdiHarif ผมกำลังเพิ่มเวอร์ชันสุดท้ายของผม1:

import * as ts from "typescript";

const options = { target: ts.ScriptTarget.ES5, module: ts.ModuleKind.CommonJS }
const program = ts.createProgram(['example.ts'], options)
const checker = program.getTypeChecker()
const sourceFile = program.getSourceFiles().filter(sf => !sf.isDeclarationFile)[0] // to filter all unwanted declaration files
const decl = sourceFile.statements[0] as ts.FunctionDeclaration
const retType = checker.getSignatureFromDeclaration(decl)!.getReturnType()
console.log(retType);

เมื่อฉันใช้ example.ts ดังต่อไปนี้:

function foo(x: number) {
  return `X = ${x}`;
}

ฉันได้คำตอบที่ถูกต้อง:

npx tsc answer.ts
node answer.js | grep 'intrinsicName'
  intrinsicName: 'string',

1 คอมไพเลอร์ Typescript ร้องเรียนเกี่ยวกับ options ที่หายไป