Make Mobile Apps with Ionic Framework 3 - Tutorial Part 7 Arrow Functions & Interfaces in TypeScript

in #programming9 years ago (edited)

typescript-2.0-awesomeness-image.jpg

Hello SteemIt community. We will talk about arrow functions and interfaces in Typescript.

Arrow Functions

So in Javascript, we can declare a function like this;

let log = function(steem) {
    console.log(steem)
}

Now in Typescript there is a shorter way to define this function. So let’s do it.

let log = (steem) => {
    console.log(steem)
}

If our function only has one line, you can even exclude the curly braces. So make this code a litle bit shorter and cleaner like this;

let log = (steem) => console.log(steem)

If you have work with C#, you have seen this before. In C#, we call this a lambda expression. In Typescript we call it a arrow function. It’s exactly the same thing. If you have one parameter in function you can even exlude the parenthesis.

let log = steem => console.log(steem)

Now, what if we don’t have any parameters? We just add empty parenthesis.

let log = () => console.log()

Interfaces

Now let’s see how we can use custom types in Typescript. So I’m gonna start by declaring a function.

let areaOfRectangle = (x, y) => {
    return x * y;
}

This function is not too bad. Here we have only 2 parameters. But sometimes when working more complex concepts you may working with function that has so many parameters. This is awful and this something you should avoid that all time. In those situations, this very likely that group of that parameters maybe all of them belong to a single concept.

let areaOfRectangle = (sides) => {
    return x * y;
}

So in this exapmle instead of asking “x” and “y” here, it’s better to ask a “sides” object. And then we call this function like this.

interface Sides {
    x: number,
    y: number
}

let areaOfRectangle = (sides: Sides) => {
    return return sides.x * sides.y;
}

areOfRectangle({
    x: 5,
    y: 8
})

Previous Chapter: Type Assertion in TypeScript

Previous Chapter: Classes in TypeScript

Sort:  

This post recieved an upvote from minnowpond. If you would like to recieve upvotes from minnowpond on all your posts, simply FOLLOW @minnowpond Please consider upvoting this comment as this project is supported only by your upvotes!

Coin Marketplace

STEEM 0.04
TRX 0.32
JST 0.081
BTC 59715.35
ETH 1564.61
USDT 1.00
SBD 0.42