Typescript basics part2

 

What I learned today

We can also apply some typescript to functions:

//function
function add(x:number, y:number):number{
    return x+y
}

Here we are expecting the return value to be a type of number


Interfaces can be used for creating custom objects:

interface customInterface {
    readonly id: number,
    name: string
    salary?: number
}

const user1: customInterface = {
    id : 1,
    name:'Joe'
}

Here we are using 'readonly' option to declare that the 'id' value cannot be changed once it is initalized.

the '?' after 'salary' means that the salary value is completely optional.


We can also use 'type'  to create custom primitives. Note that we cannot use interfaces for primitives or unions.

type example = string | number
const example1: example = 3


Generics are useful when you want to reuse some components using different types. For example, we can reuse a function using a placeholder to take in a number or string.

function getArray<T>(items:T[]):T[]{
    return new Array().concat(items)
}

let numArray = getArray<number>([1,2,3])
let strArray = getArray<string>(['a', 'b', 'c'])

numArray.push(1)

Here 'numArray' used the generics to create a new array. But once the array is created, you cannot add string types since it has been initialized with the type num.


And finally, a simple example on how to use this in React. There is an easy way to setup your repo to use typescript by using:

npx create-react-app . --template typescript

And here, we are setting the types for the props a typical React component would receive:

interface customProps {
    title: string
    text?: string
}

const Header = (props: customProps) =>{
    return (
        <div>
           {props.title}
           {props.text}
        </div>
    )
}

Comments

Popular posts from this blog

Lifecycle of React components

Styled Components

e-commerce website built with React.nodejs