gpt4 book ai didi

typescript - 如何 console.log typescript 类型

转载 作者:行者123 更新时间:2023-12-04 11:56:38 24 4
gpt4 key购买 nike

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

type TestDto = {
active: number;
user_name: string;
};
console.log(TestDto);
only refers to a type, but is being used as a value here.

最佳答案

来自 a comment :

I would like to create object property based on TS type. I would like to create JS object with property active and user_name with some default values.


您比基于类型创建对象更好的选择是做相反的事情并基于对象创建类型。这不仅为您提供了可以在运行时使用的具体内容,还可以作为属性的默认值:
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

关于typescript - 如何 console.log typescript 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67726498/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com