DEV Community

Ayyan Shaikh
Ayyan Shaikh

Posted on

Basics of Typescript

Basic Types

number : It includes all numbers like int float etc

string : All of the strings data

boolean: Only true and false , not truthy and falsy value

function add(n1:number,n2:number){
console.log(n1+n2)
}

const number1=5
const number2=9.5

add(number1,number2)

Enter fullscreen mode Exit fullscreen mode
function add(n1,n2){
    if(typeof n1!=="number"||typeof n2!=="number"){
        throw new Error("Invalid type")
    }
    console.log(n1+n2)
}

const number1=5
const number2=9.5

add(number1,number2)
Enter fullscreen mode Exit fullscreen mode

💡 Important Type Casing

In Typescript, you work with types like string or number all the times.

Important: It is string and number (etc.), NOT String, Number etc.

Boolean

function add(n1:number,n2:number,showResult:boolean){
if(showResult){
console.log(n1+n2)}
else{
return n1+n2
}
}

const number1=5
const number2=9.5
const printResult=true

add(number1,number2,printResult)
Enter fullscreen mode Exit fullscreen mode

String

function add(n1:number,n2:number,showResult:boolean,phrase:string){
let ans=n1+n2
if(showResult){
console.log(phrase+ans)}
else{
return ans
}
}

const number1=5
const number2=9.5
const printResult=true
const showPhrase="Hello"

add(number1,number2,printResult,showPhrase)
Enter fullscreen mode Exit fullscreen mode

Typescript Inference

  • Typescript Inference helps the Typescript compiler to infer its type automatically

Example:

let number=5
Enter fullscreen mode Exit fullscreen mode

let inference

Above code the typescript will infer as number as number because we assigned it a value during it’s initialization

const number=5
Enter fullscreen mode Exit fullscreen mode

const inference

Only diff in let and const is that const will assign 5 as specific number type and let will just assign number as type

  • You should ddeclare a type only if you are not assigning a value

Example:

let number;
number="Ayyan"
Enter fullscreen mode Exit fullscreen mode

Above the variable is declare without any initialized value , So here you have to otherwise any value will be added like string

let number:number
number=8
Enter fullscreen mode Exit fullscreen mode

Objects in Typescript

The objects can be typed in by using object type lIke

let obj:object ={name:"Ayyan",age:19}
Enter fullscreen mode Exit fullscreen mode

But this is not the good way of creating the objects, The correct way is to create a correct structure with predetermining the properties types of object

Example :

let obj:{name:string; age:number;}={name:"Ayyan",age:18}
console.log(obj.name)
Enter fullscreen mode Exit fullscreen mode

💡 It is recommended to let typescript infer it not by specifying

Of course object types can also be created for nested objects.

Let's say you have this JavaScript object:


1. const product = {
2.   id: 'abc1',
3.   price: 12.99,
4.   tags: ['great-offer', 'hot-and-new'],
5.   details: {
6.     title: 'Red Carpet',
7.     description: 'A great carpet - almost brand-new!'
8.   }
9. }
Enter fullscreen mode Exit fullscreen mode
This would be the **type** of such an object:
1. {
2.   id: string;
3.   price: number;
4.   tags: string[];
5.   details: {
6.     title: string;
7.     description: string;
8.   }
9. }
Enter fullscreen mode Exit fullscreen mode

So you have an object type in an object type so to say.

Arrays

We can add types for Arrays

For Example :

let obj:{name:string; age:number; hobbies:string[]}={name:"Ayyan",age:18,hobbies:["Sports"]}
console.log(obj.name)
Enter fullscreen mode Exit fullscreen mode

🎯 Tuples

Tuples are new datatype introduced in Typescript with this

  • We can fix the length of array and
  • We can take heterogeneous data means in same array both number, strings, boolean etc

    Example: Here with role we have two types in array string and number

tuples code

  • We can state the the positon of index of that types which type should be taken where

    Example: Above string at index 0 so we cannot add any other datatype same for index 1 with number type other wise it will throw error

Error code

Error code

🎯 Enums

The Enums are enumerated global constant identifiers which are used to declare a global variable, The enum property type can create a variable for you and automatically assign a number to it ,It’s syntax is

enum <name>{
"A",
"B",
"C"
}
Enter fullscreen mode Exit fullscreen mode

They are assigned with a number in increment oreder like

Enum CODE

You can even add your custom number in begining it will automatically increment further

ENUM cODE

or you can give your custom input

enum <name>{
"A"=100,
"B"="Ayyan",
"C"=true
}
Enter fullscreen mode Exit fullscreen mode

Any type

Any as it’s name suggest can take any value irrespective ,For example

let number:any
//Assign number to it
number=10
//Assign string to it
number="Ayyan"
//Assign boolean 
number=true

Enter fullscreen mode Exit fullscreen mode

If you have array you can define any as any[] so at-least it can check for array

💡 Avoid using any in any circumstance as it take away properties for which we are using typescript

🎯 Union Type

The Union type provides us with flexibility by assigning one type to variable

Syntax :

let input:number|string
let input1:number|string|boolean
let input2:number|string[]
Enter fullscreen mode Exit fullscreen mode

You can combine any Types based on your logic required , it uses | operator yo combine them

Example:

function combine(input1:number|string,input2:number|string){
    if(typeof input1==="number"&& typeof input2==="number"){
        return input1 + input2
    }else {
        return input1.toString() + input2.toString()
    }
}
let numInput=combine(1,978)
let strInput=combine("Ayyan","Shaikh")

console.log(numInput)
console.log(strInput)
Enter fullscreen mode Exit fullscreen mode

🎯Literal Types

Literal types are types you assign declaration,Example

const number=5
//Here 5 will be a literal type as const is used with it , so typescript will infer is type as number 5

//Union with literal types
function combine(input1, input2, conversion) {
    if (conversion === "as-number") {
        if (typeof input1 === "number" && typeof input2 === "number") {
            return input1 + input2;
        }
    }
    else {
        return input1.toString() + input2.toString();
    }
}
let numInput = combine(1, 978, "as-number");
let strInput = combine("Ayyan", "Shaikh", "as-text");
console.log(numInput);
console.log(strInput);
Enter fullscreen mode Exit fullscreen mode

🎯 Type aliases

The type alias is mostly used to combine two or more types or creating your custom type ,It’s syntax is

Syntax:

type <any_name> =number|string
type <any_name1> =number|string|boolean
type <any_name2> ="Ayyan"|"Saffan"//literal types
type <any_name3> =string[]|number[]|number //Array types
Enter fullscreen mode Exit fullscreen mode

You can combine any inbuilt type and create you custom type and assign it

Example:

type Combinable=string|number
function combine(input1:Combinable,input2:Combinable,conversion:"as-text"|"as-number"){
    if(conversion==="as-number"){
        if(typeof input1==="number"&& typeof input2==="number"){
            return input1 + input2
        }}else {
    return input1.toString() + input2.toString()
}
}
let numInput=combine(1,978,"as-number")
let strInput=combine("Ayyan","Shaikh","as-text")

console.log(numInput)
console.log(strInput)
Enter fullscreen mode Exit fullscreen mode

Type Aliases & Object Types

Type aliases can be used to "create" your own types. You're not limited to
storing union types though - you can also provide an alias to a
(possibly complex) object type.

For example:
1. type User = { name: string; age: number };
2. const u1: User = { name: 'Max', age: 30 }; // this works!
Enter fullscreen mode Exit fullscreen mode

This allows you to avoid unnecessary repetition and manage types centrally.

For example, you can simplify this code:
1. function greet(user: { name: string; age: number }) {
2.   console.log('Hi, I am ' + user.name);
3. }
4.  
5. function isOlder(user: { name: string; age: number }, checkAge: number) {
6.   return checkAge > user.age;
7. }
Enter fullscreen mode Exit fullscreen mode

To

1. type User = { name: string; age: number };
2.  
3. function greet(user: User) {
4.   console.log('Hi, I am ' + user.name);
5. }
6.  
7. function isOlder(user: User, checkAge: number) {
8.   return checkAge > user.age;
9. }
Enter fullscreen mode Exit fullscreen mode

🎯 Functions Type Check

In functions we can also type check everything as you have seen before parameters are given types just like that we can give types to function return type like what value it will return

Example

// Here this function will return ⬇️ number so 
function add(n1:number,n2:number):number{
return n1+n2
}

const number1=5
const number2=9.5

const output=add(number1,number2)
console.log(output)
Enter fullscreen mode Exit fullscreen mode

void return type

The void return type is used when you don’t return any thing in a function

// Here this function will return ⬇️ void because we are not returning anything  
function add(n1:number,n2:number):void{
console.log(n1+n2)
}

add(number1,number2)
Enter fullscreen mode Exit fullscreen mode

void and undefined is same but in function typescript make a distinction ,In above code if you will use :undefined it will give error but if you will add empty return it will not give error

🎯 Function Types II

Function types are types that describe a function regarding the parameters and the return value of that function.

A function type is created with this arrow function notation you know from JavaScript or at least close to that notation.You don't add curly braces here because we aren't creating an arrow function here, we are creating a function type instead.Now on the right side of this arrow,you specify the return type of the function you eventually want to be able to store in here.

Example

function add(n1:number,n2:number):number{
    return n1+n2
}

function printResult(num:number){
    console.log(`Result is ${num}`)
}
let combineValues:(num1:number,num2:number)=>number

combineValues=add

const number1=5
const number2=9.

combineValues(number1,number2)
Enter fullscreen mode Exit fullscreen mode

Now combineValues will only take the function which matches (num1:number,num2:number)=>number

Otherwise it will give error

Function Error

Callback Function Types

As function types also we can create types for callback function as same

function add(num1:number,num2:number,cb:(num3:number)=>void){//Here void means not to check for anything in return type
    const result=num1+num2
    cb(result)
}
function printResult(num:number){
    console.log(`Result is ${num}`)
}

const number1=5
const number2=9.

add(number1,number2,printResult)

Enter fullscreen mode Exit fullscreen mode

Unknown type

unknown.unknown is the type-safe counterpart of any.
Anything is assignable to unknown, but unknown isn’t assignable to anything but itself and any without a type assertion or a control flow based narrowing.
Likewise, no operations are permitted on an unknown without first asserting or narrowing to a more specific type. We have to check every-time before assigning a unknown

Example:

let userInput:unknown
let userName:string
userInput=userName //We can assign other type to unknown 
//But 
userName=userInput //We cant do that it gives error

//To do it correctly we have to assert it like

if(typeof userInput==="string){
username=userInput
}
//Now it will not give error ✅
Enter fullscreen mode Exit fullscreen mode

Never Type

In Typescript when we are certain that a particular situation will never happen, we use the never type. For example, suppose you construct a function that never returns or always throws an exception then we can use the never type on that function. Never is a new type in Typescript that denotes values that will never be encountered.

Example 1: The null can
be assigned to void but null cannot be assigned to never type variables,
nor can any other type be assigned including any.

function generateError(message:string,code:number){
throw {message,code}
} //This function will never return any value 
Enter fullscreen mode Exit fullscreen mode

Confusion with void

As soon as someone tells you that never is returned when a function never exits gracefully you intuitively want to think of it as the same as void. However, void is a Unit. never is a falsum.

A function that returns nothing returns a Unit void. However, a function that never returns (or always throws) returns never. void is something that can be assigned (without strictNullChecking) but never can never be assigned to anything other than never.

Use case of never

Mostly to give detail about function whether it can return or not something

Top comments (0)