Functions and object in typescript- DAY5 OF 100DAYSOFCODE
Meet Vaghasiya
Passionate Vue.js & Laravel Developer | JavaScript Lover | Eager to Learn
Functions:
Functions are a very important part of any programming language as it provides reusability. let's see, how to write function in js.
We have to give the type of params in circular brackets same as we give type to primitive value. if then we call the function by any other type, it will show an error. here is an example in function expression, function declaration and also using arrow function.
If you observe, then when we hover on sayHello then " (name: string) => string" is visible. where left-hand side of the arrow (name: string) is for the params of the function. and right-hand side of the arrow is a string.
if we don't provide explicitly right-hand side of the function, then the typescript set value based on the return value. if there is no return value then it will be set at the void.
we should explicitly tell typescript to take the return value. to avoid a future accidents.
Objects:
The object is key: value pair. and to mention type in typescript we can use key: datatype. let's directly show using examples.
We separate different key: value in the object using ",". but in type you need to use either a comma ", " or colon "; ". in the above example we use "; ". name:string; age:number; hobbies: string[].
You also have to give nested object types, if have any. let's say the user has locations nested object then you can give like,
领英推荐
Destructure of objects:
You think it's the same as above. we can do const {name: string} = user. right ? let's see
in this example, firstName is assigned to the string variable and gives back "meet" in the string. and first name will gives an error. in destructure works like that. so above thig will not work in destructuring. we have to mirror copy for destructure object and then assign types in mirror object as mention below.
Note: in left hand side of equal sign, stucture is same for before colon {firstName} and after colon {firstName: string} (this is mirror desturcture object).we just give datatype in right hand side of colon.. same is also applicable for latitude and longitude
Optional argument in function and object
Some times all params is not required in function or we have given default parms value in arguments. so in that types of cases you need to add question-mark before colon to show optional argument.
We can do same in object also.
That's it guys. hope you enjoy the reading. feel free to give suggestion. meeting you tommorrow. Ba byee!!