【问题标题】:How to console.log typescript type如何 console.log 打字稿类型
【发布时间】:2021-05-27 16:42:04
【问题描述】:

我知道 typescript 类型不是运行时变量。但是有什么解决方法如何打印类型名称和变量?

type TestDto = {
    active: number;  
    user_name: string;
};
console.log(TestDto);

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

我想根据 TS 类型创建对象属性。我想创建 JS 对象,其属性为 active 和 user_name 并带有一些默认值

【问题讨论】:

标签: typescript


【解决方案1】:

我想根据 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" }

Playground Link

【讨论】:

    【解决方案2】:

    正如您所写,类型在执行前被删除。 如果你想基于一个类型创建一个对象,类就可以了。 或者,如果这是您的目的,大多数 IDE 工具会在您将鼠标悬停在类型上时向您显示类型的结构。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-26
      • 1970-01-01
      • 2018-05-24
      • 2019-11-17
      • 2023-01-20
      • 1970-01-01
      • 2019-05-03
      • 2020-10-12
      相关资源
      最近更新 更多