I know that typescript type is not runtime variable. But is there any workaround how to print type name and variables?
type TestDto = {
active: number;
user_name: string;
};
console.log(TestDto);
throw only refers to a type, but is being used as a value here.
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
Use the typeof operator to check the type of a variable in TypeScript, e.g. if (typeof myVar === 'string') {} . The typeof operator returns a string that indicates the type of the value and can be used as a type guard in TypeScript.
TypeScript adds a typeof operator you can use in a type context to refer to the type of a variable or property: let s = "hello"; let n : typeof s ; let n: string. This isn't very useful for basic types, but combined with other type operators, you can use typeof to conveniently express many patterns.
I would like to create object property based on TS type. I would like to create JS object with property
active
anduser_name
with some default values.
Your better option than creating an object based on a type to do the opposite and create the type based on an object. This not only gives you something concrete you can use at runtime, it can also serve as the defaults for the properties:
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
As you wrote, types are removed before execution. If you want to create an object based on a type, classes are fine for that. Or most IDE tools show you the structure of types when you hover over them if that's your purpose.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With