Basics of Typescript
Tags: webdev, javascript, typescript, programming
Published: 2023-12-25 05:22:37

## 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

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

const number1=5
const number2=9.5

add(number1,number2)

```

```jsx
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)
```

<aside>
💡 **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.

</aside>

### Boolean

```tsx
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)
```

### String

```tsx
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)
```

## Typescript Inference

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

Example:

```tsx
let number=5
```
![let inference](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ez6tvpmghgmbhc7avyqp.png)

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

```tsx
const number=5
```

![const inference](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gkgud8vx0xq5xjtlfp14.png)

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:

```tsx
let number;
number="Ayyan"
```

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

```tsx
let number:number
number=8
```

## Objects in Typescript

The objects can be typed in by using `object` type lIke

```tsx
let obj:object ={name:"Ayyan",age:19}
```

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 :

```tsx
let obj:{name:string; age:number;}={name:"Ayyan",age:18}
console.log(obj.name)
```

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

</aside>

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

Let's say you have this JavaScript **object**:

```tsx

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. }
```

```tsx
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. }
```

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

## Arrays

We can add types for Arrays 

For Example :

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

## 🎯 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p1irq3d9oeh46cll47f7.png)
    
- 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cd2iykmu9yf7qt851kyf.png)
 
![Error code](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4uzashundmve42vq38c5.png)
    

## 🎯 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

```tsx
enum <name>{
"A",
"B",
"C"
}
```

They are assigned with a number in increment oreder like


![Enum CODE](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y05kimbn04qctxg35sps.png)

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


![ENUM cODE](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4yjf3f9uk9dc2su722aw.png)

or you can give your custom input

```tsx
enum <name>{
"A"=100,
"B"="Ayyan",
"C"=true
}
```

## Any type

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

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

```

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

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

</aside>

## 🎯 Union Type

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

Syntax :

```tsx
let input:number|string
let input1:number|string|boolean
let input2:number|string[]
```

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

Example:

```tsx
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)
```

## 🎯Literal Types

Literal types are types you assign declaration,Example

```tsx
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);
```

## 🎯 Type aliases

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

Syntax:

```tsx
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
```

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

Example:

```tsx
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)
```

## 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.

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

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

```tsx
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. }
```

To

```tsx
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. }
```

## 🎯 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

```tsx
// 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)
```

### void return type

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

```tsx
// 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)
```

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

```tsx
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)
```

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

Otherwise it will give error

![Function Error](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/udkesyhqu59g3ityyvtk.png)

### Callback Function Types

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

```tsx
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)

```

## 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:

```tsx
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 ✅
```

## Never Type

In [Typescript](https://www.geeksforgeeks.org/introduction-to-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.

```tsx
function generateError(message:string,code:number){
throw {message,code}
} //This function will never return any value 
```

### 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