#6 Objects (Fundamentals of TS)

 In object in TS, it can be written as,

let User:{name: string , id: number}={name: "", id:10}
User.name="Ram";

Like in JS, we can modify the object. But we need to specify an empty variable inside the object prior.
we can modify as given above. 
OR,

let User:{name?:string , id: number}={id:10}
User.name="Hari"

In this approach, we specify the type of the variable *if* it exists and do not have to specify an empty variable.

The first approach is preferable.

________________________________________________________________________________

If we want to make a variable read only, So we dont accidently modify it, We can say as,

let User:{readonly name: string , id: number}={name: "", id:10}
User.name="Ram";(CANNOT BE DONE)

By using readonly to a variable in an object, we then cannot modify that variable later on.


Comments

Popular posts from this blog

#8 Union Type (Advanced Types)