在 TypeScript 中,打印类型对象(即类型定义)并不像打印普通的 JavaScript 对象那样直接,因为类型信息在编译时被移除,运行时并不存在类型对象。然而,你可以通过一些技巧来间接地打印类型信息。
typeof
和 instanceof
虽然你不能直接打印类型定义,但你可以使用 typeof
和 instanceof
来获取变量的类型信息。
class MyClass {
myProperty: string;
constructor(myProperty: string) {
this.myProperty = myProperty;
}
}
const myInstance = new MyClass("Hello, TypeScript!");
console.log(typeof myInstance); // "object"
console.log(myInstance instanceof MyClass); // true
你可以使用类型断言来帮助 TypeScript 推断类型,但这在运行时不会打印类型信息。
type MyType = {
name: string;
age: number;
};
const myObject: MyType = {
name: "John",
age: 30,
};
console.log(myObject); // { name: "John", age: 30 }
console.log
和 JSON.stringify
如果你想打印一个对象的结构,可以使用 console.log
或 JSON.stringify
。
type MyType = {
name: string;
age: number;
};
const myObject: MyType = {
name: "John",
age: 30,
};
console.log(myObject); // { name: "John", age: 30 }
console.log(JSON.stringify(myObject, null, 2)); // Pretty-printed JSON
ts-morph
库如果你需要在编译时或开发工具中获取和打印类型信息,可以使用 ts-morph
库。ts-morph
是一个 TypeScript 编译器 API 的封装,允许你在代码中操作 TypeScript AST(抽象语法树)。
首先,安装 ts-morph
:
npm install ts-morph
然后,你可以使用以下代码来打印类型信息:
import { Project } from "ts-morph";
const project = new Project();
const sourceFile = project.createSourceFile("example.ts", `
type MyType = {
name: string;
age: number;
};
const myObject: MyType = {
name: "John",
age: 30,
};
`);
const myType = sourceFile.getTypeAliasOrThrow("MyType");
console.log(myType.getText());
reflect-metadata
库TypeScript 提供了一个实验性的装饰器和元数据反射 API,可以使用 reflect-metadata
库来获取一些类型信息。
首先,安装 reflect-metadata
:
npm install reflect-metadata
然后,启用 TypeScript 的实验性装饰器和元数据反射:
在 tsconfig.json
中添加:
{
"compilerOptions": {
"experimentalDecorators": true,
"emitDecoratorMetadata": true
}
}
接下来,你可以使用装饰器来获取类型信息:
import "reflect-metadata";
class MyClass {
constructor(
public myProperty: string,
public myNumber: number
) {}
}
function logType(target: any, key: string) {
const type = Reflect.getMetadata("design:type", target, key);
console.log(`${key} type: ${type.name}`);
}
class MyDecoratedClass {
@logType
myProperty: string;
@logType
myNumber: number;
constructor(myProperty: string, myNumber: number) {
this.myProperty = myProperty;
this.myNumber = myNumber;
}
}
const instance = new MyDecoratedClass("Hello", 42);
在这个示例中,logType
装饰器会在类属性上打印类型信息。
领取专属 10元无门槛券
手把手带您无忧上云