Type Script1

 TypeScript is a free and open-source programming language that is a superset of JavaScript. It was created by Microsoft in 2012 and is now one of the most popular programming languages in the world.

TypeScript adds optional static typing to JavaScript, which means that developers can write code with types and have the TypeScript compiler check that the code is valid before it is executed. This can help catch errors early on in the development process and make code more robust and easier to maintain.

Some of the key features of TypeScript include:

  • Static typing: TypeScript allows developers to specify types for variables, function parameters, and return values, which can help prevent common programming errors.
  • Object-oriented programming: TypeScript supports classes, interfaces, and other object-oriented programming concepts.
  • ES6 features: TypeScript supports many features of ECMAScript 6, such as arrow functions, template literals, and destructuring assignments.
  • Compatibility with JavaScript: TypeScript code can be compiled to JavaScript, which means that it can be used with existing JavaScript code and run in any modern browser or runtime environment.
  • Tooling support: TypeScript has a rich set of tools and integrations with popular IDEs like Visual Studio Code, making it easier to develop and maintain TypeScript code.

Overall, TypeScript is a powerful tool for building large-scale applications that are both robust and maintainable.

steps to Run Type script:

steps to run TypeScript code:

Install TypeScript: First, you need to install TypeScript globally on your computer. You can do this using npm (Node Package Manager) by running the following command in your terminal:

npm install -g typescript


  1. Write TypeScript code: Once you have installed TypeScript, you can start writing TypeScript code using a text editor or an IDE.

  2. Create a TypeScript file: Create a file with a .ts extension in your project directory and add your TypeScript code to it.

  3. Compile TypeScript code: To compile TypeScript code into JavaScript, you need to run the TypeScript compiler (tsc) in your terminal. Navigate to the directory where your TypeScript file is located and run the following command: tsc your-file-name.ts

  4. This will generate a JavaScript file with the same name as your TypeScript file but with a .js extension.

  5. 5Run the JavaScript file

Command for Security Privilege: before running type script:

Open Windows power shell as Administrator and run:

Set-ExecutionPolicy -Scope LocalMachine -ExecutionPolicy RemoteSigned



9.1 On the page, display the price of the mobile-based in three different colors. Instead of using the number in our code, represent them by string values like GoldPlatinum, PinkGold, SilverTitanium


const price: { [key: string]: number } = {
    GoldPlatinum: 799,
    PinkGold: 899,
    SilverTitanium: 999,
  };
 
  for (const color in price) {
    let colorPrice = price[color];
    //let displayColor = color.replace(/([a-z])([A-Z])/g, '$1 $2');
    console.log(`The price of the ${displayColor} mobile is $${colorPrice}`);
  }



.js code after compilation

var price = {
    GoldPlatinum: 799,
    PinkGold: 899,
    SilverTitanium: 999,
};
for (var color in price) {
    var colorPrice = price[color];
    //var displayColor = color.replace(/([a-z])([A-Z])/g, '$1 $2');
    console.log("The price of the ".concat(color, " mobile is $").concat(colorPrice));

9.2 Define an arrow function inside the event handler to filter the product array with
the selected product object using the productId received by the function.
Pass the selected product object to the next screen.


const products = [
  { id: 1, name: "Product 1", price: 10.99 },
  { id: 2, name: "Product 2", price: 24.99 },
  { id: 3, name: "Product 3", price: 18.99 }
];

function handleProductSelect(productId: number): void {
  const selectedProduct = products.filter(product => product.id === productId)[0];
  navigateToProductDetails(selectedProduct);
}

const navigateToProductDetails = (product: any) => {
  // Navigate to the next screen with the selected product object
  console.log(product);
};

// Example usage
handleProductSelect(1);

if you get compilation error like no access / access denied, open windows powershell
right click and run as administrator and type this command

 Set-ExecutionPolicy RemoteSigned

and compile again


.js file after compilation

var products = [
    { id: 1, name: "Product 1", price: 10.99 },
    { id: 2, name: "Product 2", price: 24.99 },
    { id: 3, name: "Product 3", price: 18.99 }
];
function handleProductSelect(productId) {
    var selectedProduct = products.filter(function (product) { return product.id === productId; })[0];
    navigateToProductDetails(selectedProduct);
}
var navigateToProductDetails = function (product) {
    // Navigate to the next screen with the selected product object
    console.log(product);
};
// Example usage
handleProductSelect(1);

10.1. Implement business logic for adding multiple Product values into a cart variable
which is type of string array

.ts file

interface Product {
    name: string;
    price: number;
  }
 
  const cart: string[] = [];
 
  const addProductsToCart = (...products: Product[]): void => {
    products.forEach((product: Product) => {
      const itemString: string = `${product.name} - $${product.price.toFixed(2)}`;
      cart.push(itemString);
    });
  }
 
  const product1: Product = { name: "Product A", price: 10.99 };
  const product2: Product = { name: "Product B", price: 24.99 };
  const product3: Product = { name: "Product C", price: 5.00 };
 
  addProductsToCart(product1, product2, product3);
 
  console.log(cart); // ["Product A - $10.99", "Product B - $24.99", "Product C - $5.00"]
 

In this implementation, we first define the Product interface that defines the shape of the objects that we want to add to the cart. We also declare an empty cart variable that is a type of string array.

Next, we define the addProductsToCart function that takes a rest parameter (...products) of Product type. Inside the function, we use the forEach method to iterate through each product in the rest parameter. For each product, we create an itemString variable that contains the name and price of the product as a string. We then push this itemString to the cart array.

To add products to the cart, we create some example Product objects named product1, product2, and product3. We then call the addProductsToCart function and pass in these objects as arguments.

Finally, we log the contents of the cart array to the console to verify that the products were added correctly. In this example, the output should be ["Product A - $10.99", "Product B - $24.99", "Product C - $5.00"].




.js file

var cart = [];
var addProductsToCart = function () {
    var products = [];
    for (var _i = 0; _i < arguments.length; _i++) {
        products[_i] = arguments[_i];
    }
    products.forEach(function (product) {
        var itemString = "".concat(product.name, " - $").concat(product.price.toFixed(2));
        cart.push(itemString);
    });
};
var product1 = { name: "Product A", price: 10.99 };
var product2 = { name: "Product B", price: 24.99 };
var product3 = { name: "Product C", price: 5.00 };
addProductsToCart(product1, product2, product3);
console.log(cart); // ["Product A - $10.99", "Product B - $24.99", "Product C - $5.00"]

O/p:

['Product A - $10.99', 'Product B - $24.99', 'Product C - $5.00']

Rest parameter Introduction:

In TypeScript, a rest parameter is denoted by the ellipsis (...) syntax in a function parameter declaration. A rest parameter allows a function to accept an indefinite number of arguments as an array.

Here's an example of a function that uses a rest parameter:


function myFunction(...args: number[]) { console.log(args); } myFunction(1, 2, 3); // Output: [1, 2, 3] myFunction(4, 5, 6, 7); // Output: [4, 5, 6, 7]


Comments

Popular posts from this blog

AIDS Meanstack Sample questions