TypeScript Archives - Tech Insights https://reactconf.org/category/typescript/ Unveiling Tomorrow's Tech Today, Where Innovation Meets Insight Sun, 31 Dec 2023 07:45:46 +0000 en-US hourly 1 https://wordpress.org/?v=6.6.1 https://i0.wp.com/reactconf.org/wp-content/uploads/2023/11/cropped-reactconf.png?fit=32%2C32&ssl=1 TypeScript Archives - Tech Insights https://reactconf.org/category/typescript/ 32 32 230003556 Create a Login Form in React TypeScript https://reactconf.org/create-a-login-form-in-react-typescript/ https://reactconf.org/create-a-login-form-in-react-typescript/#comments Mon, 25 Dec 2023 06:35:10 +0000 http://reactconf.org/?p=171 In this tutorial, we will learn How to Create a Login Form in React with Typescript and add styling and validation. in this post, we’ll use Vite to Create a …

The post Create a Login Form in React TypeScript appeared first on Tech Insights.

]]>
In this tutorial, we will learn How to Create a Login Form in React with Typescript and add styling and validation. in this post, we’ll use Vite to Create a React app for.

Prerequisites

Install Node.js and npm, the standard package manager for javascript.

Creating the React App

Once installed Node.js, create a new React app by running the following command with Vite.

Next, React app project name

√ Project name: ... Login_app

And give the package name

√ Package name: ... reactlogin

Select a Framework

? Select a framework: » – Use arrow keys. Return to submit.

Then select TypeScript

Open the application in vs code. Open the terminal in VS Code and run the following command

Create file Login.tsx and login.css

import { useState } from 'react'
import './Login.css'
import { BrowserRouter as Routers, Routes , Route, Navigate } from 'react-router-dom'
import HomePage from '../Home'
 

// eslint-disable-next-line @typescript-eslint/no-unused-vars
function Login(){

  const [email, setEmail] = useState("")
  const[password, setPassword] = useState("")
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const[emailError, setEmailError] = useState("")
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const[passwordError,setPasswordError]= useState("")
//  const navigate = useNavigate();

  const onButtonClick = () =>{
    setEmailError("")
    setPasswordError("")

    if("" === email){
      setEmailError("Please enter your email")
      return
    }

    if("" === password)
    {
      setPasswordError("Please enter a password")
      return
    }
    if(password.length<7){
      setPasswordError("password must be 8 character or longer")
      return
    }

    if(!/^[\w-.]+@([\w-]+\.)+[\w-]{2,4}$/.test(email)){
      setEmailError("please enter a vlid email address")
      return
    }
   
    if(email){
      return(
      <>
      {
        <Routers>
          {
          <Routes>
            <Route path='/' element={<HomePage />}>

            </Route>
          </Routes>
    }
        </Routers>
      }
       
      </>
      )
    }else{
      return <Navigate to='/Component/Login/Login'/>
    }
  //navigate("../Home")

  }

    return(
        <div className="login-box">
  <h2>Login</h2>
  <form>
    <div className="user-box">
        <input  
        value={email}
        placeholder='Enter email address here' 
        onChange={ev=> setEmail(ev.target.value)}
        className={"user-box"}      
        
        />
      
      <label className='errorLabel'>{emailError}</label>
    </div>
    <div className="user-box">
      <input 
      value={password}
      placeholder='Enter password here'
      onChange={ev=>setPassword(ev.target.value)}
      className={'user-box'}
      
      />
      <label className='errorLabel'>{passwordError}</label>
    </div>
    <input onClick={onButtonClick}
      className={"inputButton"}
      type="button"      
      value={"Submit"}
    />
  </form>
</div>     
        
)
}

export default Login

Login.css

html {
  height: 100%;
}
body {
  margin:0;
  padding:0;
  font-family: sans-serif;
  background: linear-gradient(#141e30, #446891);
}

.login-box {
  position: absolute;
  top: 50%;
  left: 50%;
  width: 400px;
  padding: 40px;
  transform: translate(-50%, -50%);
  background: rgba(0,0,0,.5);
  box-sizing: border-box;
  box-shadow: 0 15px 25px rgba(0,0,0,.6);
  border-radius: 10px;
}

.login-box h2 {
  margin: 0 0 30px;
  padding: 0;
  color: #fff;
  text-align: center;
}

.login-box .user-box {
  position: relative;
}

.login-box .user-box input {
  width: 100%;
  padding: 10px 0;
  font-size: 16px;
  color: #fff;
  margin-bottom: 30px;
  border: none;
  border-bottom: 1px solid #fff;
  outline: none;
  background: transparent;
}
.login-box .user-box label {
  position: absolute;
  top:0;
  left: 0;
  padding: 10px 0;
  font-size: 16px;
  color: #fff;
  pointer-events: none;
  transition: .5s;
}

.login-box .user-box input:focus ~ label,
.login-box .user-box input:valid ~ label {
  top: -20px;
  left: 0;
  color: #03e9f4;
  font-size: 12px;
}

.login-box form a {
  position: relative;
  display: inline-block;
  padding: 10px 20px;
  color: #03e9f4;
  font-size: 16px;
  text-decoration: none;
  text-transform: uppercase;
  overflow: hidden;
  transition: .5s;
  margin-top: 40px;
  letter-spacing: 4px
}

.login-box a:hover {
  background: #03e9f4;
  color: #fff;
  border-radius: 5px;
  box-shadow: 0 0 5px #03e9f4,
              0 0 25px #03e9f4,
              0 0 50px #03e9f4,
              0 0 100px #03e9f4;
}

.login-box a span {
  position: absolute;
  display: block;
}

.login-box a span:nth-child(1) {
  top: 0;
  left: -100%;
  width: 100%;
  height: 2px;
  background: linear-gradient(90deg, transparent, #03e9f4);
  animation: btn-anim1 1s linear infinite;
}

@keyframes btn-anim1 {
  0% {
    left: -100%;
  }
  50%,100% {
    left: 100%;
  }
}

.login-box a span:nth-child(2) {
  top: -100%;
  right: 0;
  width: 2px;
  height: 100%;
  background: linear-gradient(180deg, transparent, #03e9f4);
  animation: btn-anim2 1s linear infinite;
  animation-delay: .25s
}

@keyframes btn-anim2 {
  0% {
    top: -100%;
  }
  50%,100% {
    top: 100%;
  }
}

.login-box a span:nth-child(3) {
  bottom: 0;
  right: -100%;
  width: 100%;
  height: 2px;
  background: linear-gradient(270deg, transparent, #03e9f4);
  animation: btn-anim3 1s linear infinite;
  animation-delay: .5s
}

@keyframes btn-anim3 {
  0% {
    right: -100%;
  }
  50%,100% {
    right: 100%;
  }
}

.login-box a span:nth-child(4) {
  bottom: -100%;
  left: 0;
  width: 2px;
  height: 100%;
  background: linear-gradient(360deg, transparent, #03e9f4);
  animation: btn-anim4 1s linear infinite;
  animation-delay: .75s
}

@keyframes btn-anim4 {
  0% {
    bottom: -100%;
  }
  50%,100% {
    bottom: 100%;
  }
}

.mainContainer {
  flex-direction: column;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100vh;
}

.titleContainer {
  display: flex;
  flex-direction: column;
  font-size: 64px;
  font-weight: bolder;
  align-items: center;
  justify-content: center;
}

.resultContainer, .historyItem { 
  flex-direction: row;
  display: flex;
  width: 400px;
  align-items: center;
  justify-content: space-between;
}

.historyContainer {
  flex-direction: column;
  display: flex;
  height: 200px;
  align-items: center;
  flex-grow: 5;
  justify-content: flex-start;
}

.buttonContainer {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 260px;
}

.inputContainer {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  justify-content: center;
}

.inputContainer > .errorLabel {
  color: red;
  font-size: 12px;
}

.inputBox {
  height: 48px;
  width: 400px;
  font-size: large;
  border-radius: 8px;
  border: 1px solid grey;
  padding-left: 8px;
}
input[type="button"] {
  border: none;
  background: cornflowerblue;
  color: white;
  padding: 12px 24px;
  margin: 8px;
  font-size: 15px;
  border-radius: 8px;
  cursor: pointer;
}

Open the App.tsx and call the login function

import './App.css'
import Login from './Login'

function MyApp() {

  return (
    <>
    <Login  />     
    </>
  )
}

export default MyApp

Run the application

npm run dev

Create a Login Form in React TypeScript

See More: React Conference 2023 / 2024

The post Create a Login Form in React TypeScript appeared first on Tech Insights.

]]>
https://reactconf.org/create-a-login-form-in-react-typescript/feed/ 1 171
TypeScript Object | How to Merge Objects in TypeScript https://reactconf.org/typescript-object-how-to-merge-objects-in-typescript/ https://reactconf.org/typescript-object-how-to-merge-objects-in-typescript/#respond Fri, 15 Sep 2023 12:32:30 +0000 https://labpys.com/?p=1720 In this article, we will learn How to Merge Objects in TypeScript. To merge objects, you can use the following. Using spread operator In TypeScript, the Easiest way to merge …

The post TypeScript Object | How to Merge Objects in TypeScript appeared first on Tech Insights.

]]>
In this article, we will learn How to Merge Objects in TypeScript. To merge objects, you can use the following.

Merge Objects in TypeScript
  • spread operator
  • Object.Assign
  • Lodash merge function        

Using spread operator

In TypeScript, the Easiest way to merge objects using the spread operator. The spread operator is a feature of ES6, you will need to target ES6 or later when you compile.

Here is an Example:

const empNameObject = {
  name : 'John',
  lastname: 'pointing'
};

const empAddressObject={
  street :'Main 10th Road',
  city : 'NY'
};

const mergeObject = {
  ...empNameObject,...empAddressObject
};

console.log(mergeObject);

In the above example, the mergeObject is a new object that contains all the properties from empNameObject and em AddressObject.

Output:

{
name: ‘John’,
lastname: ‘pointing’,
street: ‘Main 10th Road’,
city: ‘NY’
}

Using Object.assign

The “Object.assign” method copies all the enumerable & own properties from one or many source objects to a target object and it is a built-in function.

This function can work similarly to a spread operator.

const empNameObject = {
  name : 'John',
  lastname: 'pointing'
};

const empAddressObject={
  street :'Main 10th Road',
  city : 'NY'
};

const empSalaryObject={
  salary : 50000,
  increment : 10
};


const mergeObjectAssign = Object.assign({}, empNameObject,empAddressObject,empSalaryObject);
 
console.log(mergeObjectAssign);

Output:

{
  name: 'John',
  lastname: 'pointing',
  street: 'Main 10th Road',
  city: 'NY',
  salary: 50000,
  increment: 10
}

Using Lodash Merge Function

The “Lodash” merge function is used to merge two or more objects together, creating a new object that contains the properties and values from the source objects It merges complex values.

import * as lodashMerge from 'lodash';
const lodashObject ={
  Email : "Fleming@test.com",  
  DisplayName: "Flemin",
  Address : {
          firstName : "Flemin@test.com",
          lastName: "Fleming",
          street:"Abc",
          city:"New york",
          state :"NY",
          zipCode: "2341"
}
};

const lodashObjectsalary ={
  salary : 45000,
  increment:{
    firstQ : 10,
    secondQ : 15
  }
};
const MergeLodashObject =  lodashMerge.merge(lodashObject,lodashObjectsalary); 

console.log(MergeLodashObject);

Output:

{
  Email: 'Fleming@test.com',
  DisplayName: 'Flemin',
  Address: {
    firstName: 'Flemin@test.com',
    lastName: 'Fleming',
    street: 'Abc',
    city: 'New york',
    state: 'NY',
    zipCode: '2341'
  },
  salary: 45000,
  increment: { firstQ: 10, secondQ: 15 }
}

More Article – remove duplicates from an Array in TypeScript

The post TypeScript Object | How to Merge Objects in TypeScript appeared first on Tech Insights.

]]>
https://reactconf.org/typescript-object-how-to-merge-objects-in-typescript/feed/ 0 1720
How to remove duplicates from an Array in TypeScript https://reactconf.org/how-to-remove-duplicates-from-an-array-in-typescript/ https://reactconf.org/how-to-remove-duplicates-from-an-array-in-typescript/#respond Thu, 14 Sep 2023 11:43:13 +0000 https://labpys.com/?p=1682 In this article, we will learn how to remove duplicates from an Array in TypeScript. Set Method The simplest and most efficient way to remove duplicates from an array is …

The post How to remove duplicates from an Array in TypeScript appeared first on Tech Insights.

]]>
In this article, we will learn how to remove duplicates from an Array in TypeScript.

Set Method

The simplest and most efficient way to remove duplicates from an array is using Set. A Set is a built-in function in a JavaScript object that stores unique values.

const setArray = new Set([1001,1020,1400,2300,1002]);
// Array.from Method

const Uniquevalue= Array.from(new Set(setArray));

// Spread Method
const Uniquevalue = [... new Set(setArray)];

console.log(Uniquevalue);

Output:

[1001, 1020, 1400, 2300, 1002]

Filter() Method

Using Filter with the ‘IndexOf’ array method, we can remove duplicates from the array object.

const Uniquevalue = [1001,1020,1400,2300,1002,6500,5001,4001,5001];
 
console.log('Filter Method'); 
const uniqueEmpcode = Uniquevalue.filter((value,index,items)=> items.indexOf(value)===index);
console.log(Uniquevalue);

Output:

[1001, 1020, 1400, 2300, 1002, 6500, 5001, 4001] 

reduce() Method

With the ‘reduce()’ method we can also remove the duplicate elements in the array.

console.log('Reduce Method');
const Uniquevalue = [1001,1020,1400,2300,1002,6500,5001,4001,5001];
 
const uniqueEmpcodereduce = Uniquevalue.reduce(
    (value,items)=> value.includes(items) ? value : [...value,items],       
    []);
console.log(uniqueEmpcodereduce);

Here is the Output:

[1001, 1020, 1400, 2300, 1002, 6500, 5001, 4001] 

More Article Convert Set into an Array in TypeScript

The post How to remove duplicates from an Array in TypeScript appeared first on Tech Insights.

]]>
https://reactconf.org/how-to-remove-duplicates-from-an-array-in-typescript/feed/ 0 1682
How to Convert Set into an Array in TypeScript https://reactconf.org/how-to-convert-set-into-an-array-in-typescript/ https://reactconf.org/how-to-convert-set-into-an-array-in-typescript/#respond Thu, 14 Sep 2023 07:34:28 +0000 https://labpys.com/?p=1673 In TypeScript, Convert the Set into an Array by using the “Array.from” function or by using the spread operator “(`...`)”. In this article, we will learn How to convert “Set” …

The post How to Convert Set into an Array in TypeScript appeared first on Tech Insights.

]]>
In TypeScript, Convert the Set into an Array by using the “Array.from” function or by using the spread operator “(`...`)”. In this article, we will learn How to convert “Set” into an Array in TypeScript.

convert set into an Array in Typescript

Using Array.from Method

Array.from” the method is used to create a new array from an iterable object.

Here is how you can use Array.from in TypeScript

const setArray = new Set([1001,1020,1400,2300,'Pointing','Stuart']);
const arry = Array.from(setArray);

console.log(arry);

Output:

[ 1001, 1020, 1400, 2300, ‘Pointing’, ‘Stuart’ ]

Using Spread Operator

const setArray = new Set([1001,1020,1400,2300,'Pointing','Stuart']);
const arrspreading = [...setArray];
console.log(arrspreading);

Related article – How to Create a Set in TypeScript

The post How to Convert Set into an Array in TypeScript appeared first on Tech Insights.

]]>
https://reactconf.org/how-to-convert-set-into-an-array-in-typescript/feed/ 0 1673
How to Create a Set in TypeScript https://reactconf.org/how-to-create-a-set-in-typescript/ https://reactconf.org/how-to-create-a-set-in-typescript/#respond Thu, 14 Sep 2023 05:05:20 +0000 https://labpys.com/?p=1654 In TypeScript, the Set is a new data structure introduced in ES6 that stores a group/collection of unique values.  The key feature of a set is that it does not …

The post How to Create a Set in TypeScript appeared first on Tech Insights.

]]>
In TypeScript, the Set is a new data structure introduced in ES6 that stores a group/collection of unique values.  The key feature of a set is that it does not allow duplicate values, but it stores only keys, not key-value pairs. In this article, we will explore How to Create a Set in TypeScript.

Create a Set in TypeScript

Create a TypeScript Set

To Create a Set in TypeScript, simply use the “Set” constructor.

let gender = new Set<string>();

gender = new Set<string>(['Male', 'Female']);

console.log(gender);

Output :

Set(2) { 'Male', 'Female' }

Set Methods

MethodsDescription
Set.add(value)Add the specified value to the Set.
set.has(value)Checks the existence of the specified value in the Set, if it is the value present in the function it returns true or else it returns false.
set.delete(value)Deletes the specified value from the Set.
set.clear()Clears all the values from the Set.
set.sizeChecks the existence of the specified value in the Set, if it is value present in the function it returns true or else it returns false.
set.values()Returns an iterator with the values of the set
set.keys()Returns an iterator with the values of the ‘Set’. Returns the same result as the values() function.
set.entries()Return an iterator object with value/value pairs.
Set.forEach()Invokes a callback on each value pair.

Set Method Examples

How to Add an Element to a ‘Set’?

You can add elements to a Set using the provided add function.

// Create a Set
let setEntries = new Set<number>();

// To Add values
setEntries.add(100);
setEntries.add(101);
setEntries.add(102);
setEntries.add(103).add(104).add(105).add(106).add(107);

How to check if a Set contains a key?

Check the existence of the specified value in the Set, using the provided function ‘has’

// check value is present or not

setEntries.has(103);
setEntries.has(110);

Get the Size of the Set?

// Get Set Size

setEntries.size;

Delete a value from Set?

// Remove a value from Set

setEntries.delete(102);

How to Remove all entries in Set?

// Clear all Set Values
setEntries.clear();

How to iterate over a Set?

We can iterate over a Set using the for-of and forEach loops.

Using for-of

let Setvalues = new Set<number>();

// Add value to Set
Setvalues.add(201);
Setvalues.add(202).add(203).add(204).add(205);
// or

const Setvalues1 = new Set([500,501,502,503,504]);

//iterate Set with for-of
for (let val of Setvalues){
    console.log(val);
}

Using forEach

// iterate entries with forEach
Setvalues.forEach(function(val){
 console.log(val);
});

//alternatively yo can use the built -in Javascript forEach function

Setvalues.forEach(val=>console.log(val));

More article – How to Create a TypeScript Map

The post How to Create a Set in TypeScript appeared first on Tech Insights.

]]>
https://reactconf.org/how-to-create-a-set-in-typescript/feed/ 0 1654
How to Create a TypeScript Map https://reactconf.org/how-to-create-a-typescript-map/ https://reactconf.org/how-to-create-a-typescript-map/#respond Tue, 12 Sep 2023 07:29:30 +0000 https://labpys.com/?p=1635 The Map is a new data structure introduced in ES6. The map allows for storing key-value entries. It is a built-in data structure in TypeScript that is similar to a …

The post How to Create a TypeScript Map appeared first on Tech Insights.

]]>
The Map is a new data structure introduced in ES6. The map allows for storing key-value entries. It is a built-in data structure in TypeScript that is similar to a JavaScript map but it has the added benefit of type checking.

In TypeScript Map class provides a type-safe way to store key-value pairs with any type of key and value.

In this article, we will learn How to Create a TypeScript Map

Create a TypeScript Map

Create a Map using the new keyword and provide the data types for keys and values.

new Map<type,type>()

To create a Map with initial key-value entries, then pass the key-value pairs as an array to the Map constructor.

let createMap = new Map<string,string>([
[“key1”,”value1”],
[“key2”,”value2”]
]);

Map Methods

To  Add, Retrieve, and  Delete Entries from the Map. These common operations are available.

MethodsDescription
Map.set(key,value)   To add entries in the map
Map.get(key) To retrieve the values for a given key from the Map.
Map.has(key) Check if a key is present in the Map. it returns true or false.
Map.delete(key) Remove the entries using its key. If the key is found and deleted, it returns true else returns false.
Map.clear()delete all entries from the Map

Here is a Code Example:

//Creating Map
let customerMap = new Map<string, number>();

// Adding the entries
customerMap.set("Fleming", 101);
customerMap.set("Raj", 102);
customerMap.set("Astle", 103);
customerMap.set("Stuart", 104);

console.log(customerMap);
// Get entries
let custcode = customerMap.get("Raj");

console.log("customer code --" + custcode);
// checking the entry if present return true else false
customerMap.has("Astle");
customerMap.has("john");

// get the Map size
let countcollection = customerMap.size;

console.log("Map size --" +countcollection);
// remove the entry
let removekey = customerMap.delete("Stuart");
console.log('deleted -  ' + removekey);
// clear all Map entries
customerMap.clear();

console.log("clear the Map Entries --" + customerMap);

Result:

Map(4) {
  'Fleming' => 101,
  'Raj' => 102,
  'Astle' => 103,
  'Stuart' => 104
}
customer code --102
Map size --4
deleted -  true
clear the Map Entries --[object Map]

How to iterate over Map

Iterate over map keys or values by using the ‘for-each’  loop. It returns an array of key-value pairs for each iteration.

Use the ‘for..of’ loop to iterate over the map.

  • Map.keys()  – to iterate over map keys
  • Map.values()  – to iterate over map values
  • Map.entries() – to iterate over map entries
  • Map – use object destructuring to iterate over map entries.

Here is a Code Example:

let customerMap = new Map<string, number>();

customerMap.set("Fleming", 101);
customerMap.set("Raj", 102);
customerMap.set("Astle", 103);
customerMap.set("Stuart", 104);

console.log("Iterate over map keys");
for (let key of customerMap.keys())
{
    console.log(key);
}


console.log("Iterate over map values");
for (let value of customerMap.values())
{
    console.log(value);
}


console.log("Iterate over map Entries");
for (let entry of customerMap.entries())
{
    console.log(entry[0],entry[1]);
}

console.log("destructuring object");
for (let [key,value] of customerMap)
{
    console.log(key,value);
}

Create a Map Using the  “Record Utility” Type

To Create a map using “Record Utility” type. It takes two parameters, the type of the keys and the types of the values.

Syntax

Record<type,type>={};

Here is a Code Example:

//Creating a map using "Record Utility" Type:

const customer : Record<string,string>={};

// assign the value to the keys of the map

customer['Stephen'] = '1001';
customer['John'] = '1075';
customer['Nathan'] = '1120';
customer['Raj'] = '1145';


console.log(customer);

Output

{ Stephen: ‘1001’, John: ‘1075’, Nathan: ‘1120’, Raj: ‘1145’ }

More articles – Convert Enum into an Array in Typescript

The post How to Create a TypeScript Map appeared first on Tech Insights.

]]>
https://reactconf.org/how-to-create-a-typescript-map/feed/ 0 1635
TypeScript Enum | How to Convert Enum into an Array in Typescript https://reactconf.org/typescript-enum-how-to-convert-enum-into-an-array-in-typescript/ https://reactconf.org/typescript-enum-how-to-convert-enum-into-an-array-in-typescript/#respond Mon, 11 Sep 2023 11:18:13 +0000 https://labpys.com/?p=1618 Enums are a set of named constants in TypeScript. Enums are useful when you have a fixed set of constants. Sometimes we need to  Convert an enum into an array …

The post TypeScript Enum | How to Convert Enum into an Array in Typescript appeared first on Tech Insights.

]]>
Enums are a set of named constants in TypeScript. Enums are useful when you have a fixed set of constants. Sometimes we need to  Convert an enum into an array in Typescript, and this can be quite easy.

In this article, we will learn How to Convert an enum into an array in Typescript with some examples.

Let’s get started,

Enums As we have discussed, define a set of named constants that exist at runtime as real objects.

TypeScript Enum

Convert numeric enum into an array

To convert a numeric enum into an array we need to use the “Object.values” with the filter function

Let’s have an example

enum gender{
    Male,
    Female,
    Others
}
console.log(Object.values(gender));

When we run this example we will get this result.

> tsc enumtoarray.ts 
> node enumtoarray.js

[ 'Male', 'Female', 'Others', 0, 1, 2 ]

Suppose if we need to filter out only the numeric value then we have to use the filter function.

Like so,

enum gender{
    Male,
    Female,
    Others
}
console.log(Object.values(gender).filter(val=>isNaN(Number(val))));
 

If we need to filter out only the string value.

enum gender{
    Male,
    Female,
    Others
}

console.log(Object.values(gender).filter(val=>!isNaN(Number(val))));

Here is the result:

[ 'Male', 'Female', 'Others' ]
[ 0, 1, 2 ]

Convert a string enum into an array

To convert a string enum into an array we have to use the Object.values or  Object.key functions

Let’s have an example

enum department{
    CS = 'Computer Science Engg',
    Mech = 'Mechanical Engineering',
    EC = 'Electronic and Communication Engg',
    CV = 'Civil Engineering'
}

console.log(Object.keys(department));
console.log(Object.values(department));

Here is the output:

[ 'CS', 'Mech', 'EC', 'CV' ]
[
  'Computer Science Engg',
  'Mechanical Engineering',
  'Electronic and Communication Engg',
  'Civil Engineering'
]

Converting an Enums Key-value pair into an array

To transform an enum into an array of key-value pairs, we need to use the Object.entries() Method with applying a filter function to remove any pairs where the value is not a number.

const Gendernum : [string,number][]=Object.entries(gender)
.filter(([key,value])=> typeof value === 'number')
.map(([key,value])=> [key,value as number]);

console.log(Gendernum);

Result:

[ [ 'Male', 0 ], [ 'Female', 1 ], [ 'Others', 2 ] ]

enum department{
    CS = 'Computer Science Engg',
    Mech = 'Mechanical Engineering',
    EC = 'Electronic and Communication Engg',
    CV = 'Civil Engineering'
}
export const gendermodel:{
    value: string;
    key : string;
}[]=Object.entries(department)
.map(([key,value])=>({key,value}));

console.log(gendermodel);

Result:

[
  { key: 'CS', value: 'Computer Science Engg' },
  { key: 'Mech', value: 'Mechanical Engineering' },
  { key: 'EC', value: 'Electronic and Communication Engg' },
  { key: 'CV', value: 'Civil Engineering' }
]

More Articles – How to Create a Multi-Select Dropdown List in Angular

The post TypeScript Enum | How to Convert Enum into an Array in Typescript appeared first on Tech Insights.

]]>
https://reactconf.org/typescript-enum-how-to-convert-enum-into-an-array-in-typescript/feed/ 0 1618