如何console.log打字稿类型

7ke*_*7ay 27 typescript

我知道打字稿类型不是运行时变量。但是有什么解决方法可以打印类型名称和变量吗?

type TestDto = {
    active: number;  
    user_name: string;
};
Run Code Online (Sandbox Code Playgroud)
console.log(TestDto);
Run Code Online (Sandbox Code Playgroud)

only refers to a type, but is being used as a value here.

我想根据 TS 类型创建对象属性。我想创建具有活动属性和user_name一些默认值的JS 对象

VLA*_*LAZ 6

我想根据 TS 类型创建对象属性。我想创建带有属性activeuser_name一些默认值的 JS 对象。

与基于类型创建对象相比,您更好的选择是执行相反的操作并基于对象创建类型。这不仅为您提供了可以在运行时使用的具体内容,还可以作为属性的默认值:

const DefaultTestDto = {
    active: -1,
    user_name: "",
}

type TestDto = typeof DefaultTestDto;


const newDto1: TestDto = {...DefaultTestDto};
newDto1.user_name = "Fred";
//or
const newDto2: TestDto = Object.assign({}, DefaultTestDto, {user_name: "Barney"});

console.log(newDto1); // { "active": -1, "user_name": "Fred" } 
console.log(newDto2); // { "active": -1, "user_name": "Barney" }
Run Code Online (Sandbox Code Playgroud)

游乐场链接