You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在TypeScript中输出含类型信息的函数原始源码

Great question! The core problem here is that once TypeScript compiles down to JavaScript, the original TS source (including those handy type annotations) doesn’t exist at runtime anymore. All your code is running as plain JS, which is why console.log(fn) spits out the stripped, type-free version you’re seeing.

Let’s break down a few practical ways to grab that original TypeScript source code, complete with type info:

1. Use Source Maps to Map JS Back to TS (Runtime Trick)

If you’re running your code in an environment that supports source maps (like browsers or Node.js with source map support turned on), you can reverse-engineer the original TS code from the transpiled JS.

First, make sure source maps are enabled in your tsconfig.json:

{
  "compilerOptions": {
    "sourceMap": true,
    "inlineSources": true // Optional: shoves the original TS code right into the source map file
  }
}

Then, use a library like source-map at runtime to parse the source map. You’ll need to track the position of your function in the JS output, then map that back to the corresponding line in your TS file. This works even for functions using this—you’ll get the original TS code with the this context intact, which is way more readable than the transpiled JS version.

2. Store the Source as a String (Quick & Dirty)

A super straightforward workaround is to keep your function’s TS source as a string literal alongside the function itself. This way, you always have the original code handy:

// Store the exact TS source as a string
const fnSource = `function (a: number, b: number) { return a + b; }`;
// Create the runtime function
const fn = ((a: number, b: number) => a + b);

console.log("Original TS Code:", fnSource);

For more complex functions, you could set up a build tool (like Webpack or Rollup) with a plugin that automatically extracts function source code and attaches it as a property to the function object. That way you don’t have to manually duplicate the code.

3. Parse the TS AST at Build Time (For Static Analysis)

If you only need the source code during your build process (not at runtime), you can use TypeScript’s own AST API to parse your code and yank out function definitions. Here’s a quick example:

import * as ts from 'typescript';

// Your TS code as a string
const tsCode = `var fn = function (a:number, b:number) { return a + b; };`;
const sourceFile = ts.createSourceFile('temp.ts', tsCode, ts.ScriptTarget.Latest);

// Traverse the AST to find the function
ts.forEachChild(sourceFile, node => {
  if (ts.isVariableStatement(node)) {
    const decl = node.declarationList.declarations[0];
    if (ts.isFunctionExpression(decl.initializer)) {
      // Grab the exact source text of the function
      const fnSource = tsCode.substring(decl.initializer.getStart(), decl.initializer.getEnd());
      console.log("Original TS Function:", fnSource);
    }
  }
});

This will give you the full TS source of the function, including type annotations. You can hook this into your build pipeline to generate metadata files that you can reference later.

4. Decorators for Class Methods

If your functions are class methods, you can use TypeScript decorators to capture their source code at compile time. First, enable these settings in tsconfig.json:

{
  "compilerOptions": {
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true
  }
}

Then write a decorator that uses the AST approach above to extract the method’s source code, and attach it as metadata to the method or class. This is great if you need to track source code for methods that use this heavily.

A Quick Reality Check

It’s important to remember: TypeScript is a compile-to-JS language, so there’s no native way to access the original TS source or type info at runtime without extra setup. The approaches above work because they either preserve the source upfront, or map back to it using build-time/debugging tools.

Hopefully one of these methods fits your use case!

内容的提问来源于stack exchange,提问作者olidem

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 14:34:11