Skip to content

Basic types in TS

Course: Typescript - chapter 4

**number**, **string**, **boolean**, **null**, **undefined**.

Let’s create some simple applications using these types -

💡 Thing to learn - How to give types to arguments of a function

Write a function that greets a user given their first name. Argument - firstName

Logs - Hello {firstName}

Doesn’t return anything

Solution
function greet(firstName: string) {
console.log("Hello " + firstName);
}
greet("harkirat");

💡 Thing to learn - How to assign a return type to a function

Write a function that calculates the sum of two functions

Code
function sum(a: number, b: number): number {
return a + b;
}
console.log(sum(2, 3));

Problem 3 - Return true or false based on if a user is 18+

Section titled “Problem 3 - Return true or false based on if a user is 18+”

💡 Thing to learn - Type inference

Function name - isLegal

Code
function isLegal(age: number) {
if (age > 18) {
return true;
} else {
return false
}
}
console.log(isLegal(2));

Create a function that takes another function as input, and runs it after 1 second.

Code
function delayedCall(fn: () => void) {
setTimeout(fn, 1000);
}
delayedCall(function() {
console.log("hi there");
})