我知道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类型创建对象属性。我想创建属性为active和user_name
的JS对象,并使用一些默认值
我想基于TS类型创建对象属性。我想创建具有属性
active
和user_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" }
游乐场链接
正如您所写的,类型在执行之前被删除。如果你想基于类型创建一个对象,类就可以了。或者,当你将鼠标悬停在类型上时,大多数IDE工具都会向你显示类型的结构(如果这是你的目的的话(。