Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to console.log typescript type

Tags:

typescript

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

like image 314
7kene6k7ay Avatar asked May 27 '21 16:05

7kene6k7ay


People also ask

How do you check the data type of a variable in TypeScript?

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.

What is typeof 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.


2 Answers

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.

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

like image 73
VLAZ Avatar answered Sep 27 '22 23:09

VLAZ


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.

like image 30
kasymbayaman Avatar answered Sep 27 '22 23:09

kasymbayaman