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.
When we need a value that may be of either types like string or number, then we may use union type. It can be written as; function( weight: number | string ){ if(typeof weight === "number"){ return weight * 2;} else{ return parseInt(weight)*2;} Here, the weight may either be number or a string. To make the weight act as a number, we use IF where if the (type of weight === number) so that the weight can act as a number ELSE it shall act as a string.
Comments
Post a Comment