create account

Deep Dive into Object and Function with TypeScript and JavaScript by superoo7

View this thread on: hive.blogpeakd.comecency.com
· @superoo7 · (edited)
$43.30
Deep Dive into Object and Function with TypeScript and JavaScript
In this post, I am going to deep dive into Modern JavaScript and TypeScript way of dealing with Object and Function. Bonus: Generics in TypeScript.

__Previous Topic:__
- [Getting Started with TypeScript](https://steemit.com/utopian-io/@superoo7/get-started-with-typescript)
- [TypeScript Data Type](https://steemit.com/utopian-io/@superoo7/typescript-data-types)

<center>
![bynNY5dJ.jpg](https://res.cloudinary.com/hpiynhbhq/image/upload/v1514856422/a8mr1orqfa10shbzmaam.jpg)
</center>
[Source](https://twitter.com/typescriptlang)

## Object literal
### In JavaScript/TypeScript
Object is a quite common data type in JavaScript and TypeScript. In this section, I will talk about some of the feature that TypeScript had, but not all JavaScript platform has.

- normal object
```
let obj = {
	round: true,
	name: "circle",
	edge: 0
};
```

- object in ES6
Object in ES6 offer prototype inside the object, string interpolation and more...
```
let world = "Earth";
let animal = {
	__proto__: AnimalObject.prototype,
	species: "Dog",
	name: "Bob",
	world,
	[`${world}`]: true,
};
```

- simple object destructure
In ES6, we can destructure object with this method.
```
let someone = {
	name: "Bob",
	age: 3
};
const {name, age} = someone;
console.log(`${name} is ${age} years old`); // Bob is 3 years old
```

- deep nested object destructure
If the object is deeply nested, it still can be done.
```
let someone = {
	name: "Bob",
	age: 30,
	skills: {
		web_dev: {
			html: {experience: "4 years"},
			css: {experience: "1 year"},
			javascript: {experience: "1 year"}
		}
	}
};
let {
	name, 
	age, 
	skills: {web_dev: skill}
} = someone;
```

output:

<center>
![Screen Shot 2018-01-02 at 8.53.23 PM.png](https://res.cloudinary.com/hpiynhbhq/image/upload/v1514902850/hl1wjzzqyqufxmi8twgf.png)
</center>

- Rest and Spread Properties
This is a bit like pattern matching in any functional language (e.g. Elixir), where we seek what the data looks like on our right, and we try to extract out on the left.

This is available to JS just like how spread operator in arrays. These features are available to TypeScript.

> Still in proposal stage 3. I tested with node v8.9.2

__Rest__ (extract out)

```
let colors = { r: 0, g: 120, b: 100 };
let { r, ...others } = colors;
console.log(others); // { g: 120, b: 100 }
```

__Spread__ (merge in)

```
let rgb = { r: 0, g: 120, b: 100 };
let rgba = { ...rgb, a: 0.2}
console.log(rgba); // { r: 0, g: 120, b: 100, a: 0.2 }
```

This is one of my favourite feature in the proposal and TypeScript.

Imagine this case of scenario, you had to add a new `a` into rgb. The old way of doing it:

```
let rgb = { r: 0, g: 120, b: 100 };
let rgba = rgb;
rgba.a = 0.2
```

The code will become more messier when there is more properties!.

- Getter and Setter
In OOP language, this is the common approach to access private data to achieve Encapsulation.

`Getter` - return value of the property

`Setter` -set the value of the property 

```
var employee = {
    first: "Boris",
    last: "Sergeev",
    get fullName() {
        return this.first + " " + this.last;
    },
    set fullName(value) {
        var parts = value.toString().split(" ");
        this.first = parts[0] || "";
        this.last = parts[1] || "";
    },
    email: "boris.sergeev@example.com"
};
console.log(employee.fullName); //Boris Sergeev
employee.fullName = "Alex Makarenko";
console.log(employee.first);//Alex
console.log(employee.last);//Makarenko
console.log(employee.fullName);//Alex Makarenko
```
[source](https://stackoverflow.com/a/40241468/7514001)

## Functions Types
In TypeScript, when we want to define how a function shape looks like.


```
let register: (firstname: string, lastname: string) => User; // declare function type
register = (firstname, lastname) => (new User()); // a function value
```

### Interface to define function types
```
interface newUser {
	(firstname: string, lastname: string): User
}
let register: newUser = (firstname, lastname) => (new User()); 
```

### Optional Parameters
And TypeScript, assumes every argument in the function is required. However, you can use optional to state that that argument is optional.

The syntax is just like SwiftLang with `?`.

```
function createAnimal(
						eyes: number,
						wings?: number,
						tail?: boolean
						) {...}
```

### Default Parameters Value
Same as ES6, there is default value for TypeScript.

```
function createAnimal(
						eyes: number,
						wings?: number,
						tail?: boolean,
						alive: boolean = true
						) {...}
```

### Rest Parameters
`Rest` is what I have shown just now.

``` 
function addition(base: number, ...others: number[]) {...};
addition(1,2,3,4,5);
addition(1,2,3);
```


## Generics in TypeScript
- allow us to reuse code accross many types, interfaces and functions.

```
function makeFive<T>(x: T): T[] {
	return [ x, x, x, x, x ];
}
let num: number[] = makeFive(3);
let foods: string[] = makeFive("FOOD");
```

- Array also can be express this way

```
let cards = Array<[Suit, CardNumber]>(52);
```

- Promise also

```
let data: Promise<Response> = fetch("https://google.com");
```

<hr>

<br>

That's the end of the description on Object and Function with Modern JavaScript and TypeScript. TypeScript already have more features than JavaScript, and JavaScript team (TC39) are slowly implement some features from TypeScript!

<br /><hr/><em>Posted on <a href="https://utopian.io/utopian-io/@superoo7/deep-dive-into-object-and-function-with-typescript-and-javascript">Utopian.io -  Rewarding Open Source Contributors</a></em><hr/>
👍  , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , and 9 others
properties (23)
authorsuperoo7
permlinkdeep-dive-into-object-and-function-with-typescript-and-javascript
categoryutopian-io
json_metadata"{"community":"utopian","app":"utopian/1.0.0","format":"markdown","repository":{"id":20929025,"name":"TypeScript","full_name":"Microsoft/TypeScript","owner":{"login":"Microsoft","id":6154722,"avatar_url":"https://avatars2.githubusercontent.com/u/6154722?v=4","gravatar_id":"","url":"https://api.github.com/users/Microsoft","html_url":"https://github.com/Microsoft","followers_url":"https://api.github.com/users/Microsoft/followers","following_url":"https://api.github.com/users/Microsoft/following{/other_user}","gists_url":"https://api.github.com/users/Microsoft/gists{/gist_id}","starred_url":"https://api.github.com/users/Microsoft/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/Microsoft/subscriptions","organizations_url":"https://api.github.com/users/Microsoft/orgs","repos_url":"https://api.github.com/users/Microsoft/repos","events_url":"https://api.github.com/users/Microsoft/events{/privacy}","received_events_url":"https://api.github.com/users/Microsoft/received_events","type":"Organization","site_admin":false},"private":false,"html_url":"https://github.com/Microsoft/TypeScript","description":"TypeScript is a superset of JavaScript that compiles to clean JavaScript output.","fork":false,"url":"https://api.github.com/repos/Microsoft/TypeScript","forks_url":"https://api.github.com/repos/Microsoft/TypeScript/forks","keys_url":"https://api.github.com/repos/Microsoft/TypeScript/keys{/key_id}","collaborators_url":"https://api.github.com/repos/Microsoft/TypeScript/collaborators{/collaborator}","teams_url":"https://api.github.com/repos/Microsoft/TypeScript/teams","hooks_url":"https://api.github.com/repos/Microsoft/TypeScript/hooks","issue_events_url":"https://api.github.com/repos/Microsoft/TypeScript/issues/events{/number}","events_url":"https://api.github.com/repos/Microsoft/TypeScript/events","assignees_url":"https://api.github.com/repos/Microsoft/TypeScript/assignees{/user}","branches_url":"https://api.github.com/repos/Microsoft/TypeScript/branches{/branch}","tags_url":"https://api.github.com/repos/Microsoft/TypeScript/tags","blobs_url":"https://api.github.com/repos/Microsoft/TypeScript/git/blobs{/sha}","git_tags_url":"https://api.github.com/repos/Microsoft/TypeScript/git/tags{/sha}","git_refs_url":"https://api.github.com/repos/Microsoft/TypeScript/git/refs{/sha}","trees_url":"https://api.github.com/repos/Microsoft/TypeScript/git/trees{/sha}","statuses_url":"https://api.github.com/repos/Microsoft/TypeScript/statuses/{sha}","languages_url":"https://api.github.com/repos/Microsoft/TypeScript/languages","stargazers_url":"https://api.github.com/repos/Microsoft/TypeScript/stargazers","contributors_url":"https://api.github.com/repos/Microsoft/TypeScript/contributors","subscribers_url":"https://api.github.com/repos/Microsoft/TypeScript/subscribers","subscription_url":"https://api.github.com/repos/Microsoft/TypeScript/subscription","commits_url":"https://api.github.com/repos/Microsoft/TypeScript/commits{/sha}","git_commits_url":"https://api.github.com/repos/Microsoft/TypeScript/git/commits{/sha}","comments_url":"https://api.github.com/repos/Microsoft/TypeScript/comments{/number}","issue_comment_url":"https://api.github.com/repos/Microsoft/TypeScript/issues/comments{/number}","contents_url":"https://api.github.com/repos/Microsoft/TypeScript/contents/{+path}","compare_url":"https://api.github.com/repos/Microsoft/TypeScript/compare/{base}...{head}","merges_url":"https://api.github.com/repos/Microsoft/TypeScript/merges","archive_url":"https://api.github.com/repos/Microsoft/TypeScript/{archive_format}{/ref}","downloads_url":"https://api.github.com/repos/Microsoft/TypeScript/downloads","issues_url":"https://api.github.com/repos/Microsoft/TypeScript/issues{/number}","pulls_url":"https://api.github.com/repos/Microsoft/TypeScript/pulls{/number}","milestones_url":"https://api.github.com/repos/Microsoft/TypeScript/milestones{/number}","notifications_url":"https://api.github.com/repos/Microsoft/TypeScript/notifications{?since,all,participating}","labels_url":"https://api.github.com/repos/Microsoft/TypeScript/labels{/name}","releases_url":"https://api.github.com/repos/Microsoft/TypeScript/releases{/id}","deployments_url":"https://api.github.com/repos/Microsoft/TypeScript/deployments","created_at":"2014-06-17T15:28:39Z","updated_at":"2018-01-02T14:01:53Z","pushed_at":"2018-01-02T12:03:48Z","git_url":"git://github.com/Microsoft/TypeScript.git","ssh_url":"git@github.com:Microsoft/TypeScript.git","clone_url":"https://github.com/Microsoft/TypeScript.git","svn_url":"https://github.com/Microsoft/TypeScript","homepage":"http://www.typescriptlang.org","size":495962,"stargazers_count":29495,"watchers_count":29495,"language":"TypeScript","has_issues":true,"has_projects":true,"has_downloads":true,"has_wiki":true,"has_pages":true,"forks_count":4327,"mirror_url":null,"archived":false,"open_issues_count":2774,"license":{"key":"apache-2.0","name":"Apache License 2.0","spdx_id":"Apache-2.0","url":"https://api.github.com/licenses/apache-2.0"},"forks":4327,"open_issues":2774,"watchers":29495,"default_branch":"master","score":149.85713},"pullRequests":[],"platform":"github","type":"tutorials","tags":["utopian-io","javascript","programming","web","teammalaysia"],"links":["https://steemit.com/utopian-io/@superoo7/get-started-with-typescript","https://steemit.com/utopian-io/@superoo7/typescript-data-types","https://twitter.com/typescriptlang","https://stackoverflow.com/a/40241468/7514001","https://utopian.io/utopian-io/@superoo7/deep-dive-into-object-and-function-with-typescript-and-javascript"],"image":["https://res.cloudinary.com/hpiynhbhq/image/upload/v1514856422/a8mr1orqfa10shbzmaam.jpg","https://res.cloudinary.com/hpiynhbhq/image/upload/v1514902850/hl1wjzzqyqufxmi8twgf.png"],"moderator":{"account":"manishmike10","reviewed":true,"pending":false,"flagged":false}}"
created2018-01-02 14:26:18
last_update2018-01-06 22:12:36
depth0
children6
last_payout2018-01-09 14:26:18
cashout_time1969-12-31 23:59:59
total_payout_value30.340 HBD
curator_payout_value12.964 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length5,571
author_reputation27,763,618,634,121
root_title"Deep Dive into Object and Function with TypeScript and JavaScript"
beneficiaries
0.
accountutopian.pay
weight2,500
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id26,568,964
net_rshares4,473,178,715,543
author_curate_reward""
vote details (73)
@arcange ·
WARNING - The message you received from @tripadvisor.com is a CONFIRMED SCAM! DO NOT FOLLOW the instruction in the memo! For more information, read this post: https://steemit.com/steemit/@arcange/scammer-reported-tripadvisor-com
properties (22)
authorarcange
permlinkre-deep-dive-into-object-and-function-with-typescript-and-javascript-20180102t234134000z
categoryutopian-io
json_metadata{"image":["http://i.cubeupload.com/d1Dr28.png"]}
created2018-01-02 22:41:33
last_update2018-01-02 22:41:33
depth1
children1
last_payout2018-01-09 22:41:33
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length228
author_reputation1,146,622,988,969,610
root_title"Deep Dive into Object and Function with TypeScript and JavaScript"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id26,648,016
net_rshares0
@superoo7 ·
Thanks @arcange
properties (22)
authorsuperoo7
permlinkre-arcange-re-deep-dive-into-object-and-function-with-typescript-and-javascript-20180102t224428089z
categoryutopian-io
json_metadata{"tags":["utopian-io"],"users":["arcange"],"app":"steemit/0.1"}
created2018-01-02 22:44:30
last_update2018-01-02 22:44:30
depth2
children0
last_payout2018-01-09 22:44:30
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length15
author_reputation27,763,618,634,121
root_title"Deep Dive into Object and Function with TypeScript and JavaScript"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id26,648,379
net_rshares0
@manishmike10 ·
Thank you for the contribution. It has been approved.

You can contact us on [Discord](https://discord.gg/UCvqCsx).
**[[utopian-moderator]](https://utopian.io/moderators)**
properties (22)
authormanishmike10
permlinkre-superoo7-deep-dive-into-object-and-function-with-typescript-and-javascript-20180103t161019418z
categoryutopian-io
json_metadata{"tags":["utopian-io"],"community":"utopian","app":"utopian/1.0.0"}
created2018-01-03 16:10:21
last_update2018-01-03 16:10:21
depth1
children0
last_payout2018-01-10 16:10:21
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length172
author_reputation20,399,732,899,016
root_title"Deep Dive into Object and Function with TypeScript and JavaScript"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id26,812,944
net_rshares0
@minnowsupport ·
<p>Congratulations!  This post has been upvoted from the communal account, @minnowsupport, by superoo7 from the Minnow Support Project.  It's a witness project run by aggroed, ausbitbank, teamsteem, theprophet0, someguy123, neoxian, followbtcnews/crimsonclad, and netuoso.  The goal is to help Steemit grow by supporting Minnows and creating a social network.  Please find us in the <a href="https://discord.gg/HYj4yvw">Peace, Abundance, and Liberty Network (PALnet) Discord Channel</a>.  It's a completely public and open space to all members of the Steemit community who voluntarily choose to be there.</p>

<p>If you would like to delegate to the Minnow Support Project you can do so by clicking on the following links: <a href="https://v2.steemconnect.com/sign/delegateVestingShares?delegator=&amp;delegatee=minnowsupport&amp;vesting_shares=102530.639667%20VESTS">50SP</a>, <a href="https://v2.steemconnect.com/sign/delegateVestingShares?delegator=&amp;delegatee=minnowsupport&amp;vesting_shares=205303.639667%20VESTS">100SP</a>, <a href="https://v2.steemconnect.com/sign/delegateVestingShares?delegator=&amp;delegatee=minnowsupport&amp;vesting_shares=514303.639667%20VESTS">250SP</a>, <a href="https://v2.steemconnect.com/sign/delegateVestingShares?delegator=&amp;delegatee=minnowsupport&amp;vesting_shares=1025303.639667%20VESTS">500SP</a>, <a href="https://v2.steemconnect.com/sign/delegateVestingShares?delegator=&amp;delegatee=minnowsupport&amp;vesting_shares=2053030.639667%20VESTS">1000SP</a>, <a href="https://v2.steemconnect.com/sign/delegateVestingShares?delegator=&amp;delegatee=minnowsupport&amp;vesting_shares=10253030.639667%20VESTS">5000SP</a>.  <strong>Be sure to leave at least 50SP undelegated on your account.</strong></p>
properties (22)
authorminnowsupport
permlinkre-superoo7-deep-dive-into-object-and-function-with-typescript-and-javascript-20180102t153255487z
categoryutopian-io
json_metadata{"tags":["utopian-io"],"app":"cosgrove/0.0.2"}
created2018-01-02 15:32:54
last_update2018-01-02 15:32:54
depth1
children0
last_payout2018-01-09 15:32:54
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length1,746
author_reputation148,902,805,319,183
root_title"Deep Dive into Object and Function with TypeScript and JavaScript"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id26,581,293
net_rshares0
@tripadvisor.com ·
 
**Get your post resteemed over 90000+ followers and get upto $19+ value Upvote. Your post will skyrocket and give you maximum exposer.** 

> **Send 1 SBD or STEEM to steemitrobot with your post url you will get your post share over 30000+ followers and 1 upvote $1.5+ value. Plus Get**

> **Send 3 SBD or STEEM to steemitrobot  with your post url you will get your post share over 60000+ followers and 1 upvote $5+ value. Plus Get**

> **Send 5 SBD or STEEM to steemitrobot with your post url you will get your post share over 60000+ followers and 1 upvote $9+ value. Plus Get**

> **Send 6 SBD or STEEM to steemitrobot with your post url you will get your post share over 90000+ followers and 1 upvote $11+ value. Plus Get**

> **Send 10 SBD or STEEM to steemitrobot with your post url you will get your post share over 90000+ followers and 1 upvote $19+ value. Plus Get**

See our all pakages at: http://www.whaleboostup.ml
👎  
properties (23)
authortripadvisor.com
permlinkre-superoo7-deep-dive-into-object-and-function-with-typescript-and-javascript-20180102t143723501z
categoryutopian-io
json_metadata{"tags":["utopian-io"],"community":"busy","app":"busy/2.2.0"}
created2018-01-02 14:26:45
last_update2018-01-02 14:26:45
depth1
children0
last_payout2018-01-09 14:26:45
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length927
author_reputation-905,234,436,028
root_title"Deep Dive into Object and Function with TypeScript and JavaScript"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id26,569,052
net_rshares-951,240,914,201
author_curate_reward""
vote details (1)
@utopian-io ·
### Hey @superoo7 I am @utopian-io. I have just upvoted you!
#### Achievements
- You have less than 500 followers. Just gave you a gift to help you succeed!
- Seems like you contribute quite often. AMAZING!
#### Suggestions
- Contribute more often to get higher and higher rewards. I wish to see you often!
- Work on your followers to increase the votes/rewards. I follow what humans do and my vote is mainly based on that. Good luck!
#### Get Noticed!
- Did you know project owners can manually vote with their own voting power or by voting power delegated to their projects? Ask the project owner to review your contributions!
#### Community-Driven Witness!
I am the first and only Steem Community-Driven Witness. <a href="https://discord.gg/zTrEMqB">Participate on Discord</a>. Lets GROW TOGETHER!
- <a href="https://v2.steemconnect.com/sign/account-witness-vote?witness=utopian-io&approve=1">Vote for my Witness With SteemConnect</a>
- <a href="https://v2.steemconnect.com/sign/account-witness-proxy?proxy=utopian-io&approve=1">Proxy vote to Utopian Witness with SteemConnect</a>
- Or vote/proxy on <a href="https://steemit.com/~witnesses">Steemit Witnesses</a>

[![mooncryption-utopian-witness-gif](https://steemitimages.com/DQmYPUuQRptAqNBCQRwQjKWAqWU3zJkL3RXVUtEKVury8up/mooncryption-s-utopian-io-witness-gif.gif)](https://steemit.com/~witnesses)

**Up-vote this comment to grow my power and help Open Source contributions like this one. Want to chat? Join me on Discord https://discord.gg/Pc8HG9x**
properties (22)
authorutopian-io
permlinkre-superoo7-deep-dive-into-object-and-function-with-typescript-and-javascript-20180104t072609547z
categoryutopian-io
json_metadata{"tags":["utopian-io"],"community":"utopian","app":"utopian/1.0.0"}
created2018-01-04 07:26:09
last_update2018-01-04 07:26:09
depth1
children0
last_payout2018-01-11 07:26:09
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length1,506
author_reputation152,955,367,999,756
root_title"Deep Dive into Object and Function with TypeScript and JavaScript"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id26,969,719
net_rshares0