Header image

Blog 14 Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test

19/04/2022

492

Table of contents

  • What is TypeScript?
  • Basic typing
  • What is TypeScript any type?
  • Why does TypeScript provide any?

TypeScript is a strongly typed programming language that builds on JavaScript, giving you a better ability to detect errors and describe your code. But sometimes you don’t know the exact type of value that you’re using because it comes from user input or a third-party API.

In this case, you want to skip the type checking and allow the value to pass through the compile check. The TypeScript any type is the perfect solution for you because if you use it, the TypeScript compiler will not complain about the type issue.

This blog will help you understand the any type in TypeScript but before doing that, let’s begin with some basic concepts first!

What is TypeScript?

TypeScript checks a program for errors before execution, and does so based on the kinds of values, it’s a static type checker.

Superset of JavaScript

TypeScript is a language that is a superset of JavaScript: JS syntax is therefore legal TS. However, TypeScript is a typed superset, meaning that it adds rules about how different kinds of values can be used.

Runtime Behavior

TypeScript is also a programming language that preserves the runtime behavior of JavaScript. This means that if you move code from JavaScript to TypeScript, it is guaranteed to run the same way, even if TypeScript thinks that the code has type errors.

Erased Types

Roughly speaking, once TypeScript’s compiler is done with checking your code, it erases the types to produce the resulting compiled code. This means that once your code is compiled, the resulting plain JS code has no type information.

An easy way of understanding TypeScript

  • A language
  • A superset of JavaScript
  • Preserver the runtime behavior of JavaScript
  • Type checker layer

JavaScript + Types = TypeScript

Basic typing

Type annotations

TypeScript uses type annotations to explicitly specify types for identifiers such as variables, functions, objects, etc.

// Syntax
: type

Once an identifier is annotated with a type, it can be used as that type only. If the identifier is used as a different type, the TypeScript compiler will issue an error.

let counter: number;
counter = 1;
counter = 'Hello'; // Error: Type '"Hello"' is not assignable to type 'number'.

The following shows other examples of type annotations:

let name: string = 'John';
let age: number = 25;
let active: boolean = true;
// Array
let names: string[] = ['John', 'Jane', 'Peter', 'David', 'Mary'];
// Object
let person: {
  name: string;
  age: number
};
person = {
  name: 'John',
  age: 25
}; // Valid
// Function
let sayHello : (name: string) => string;
sayHello = (name: string) => {
  return `Hello ${name}`;
};

Type inference

Type inference describes where and how TypeScript infers types when you don’t explicitly annotate them. For example:

// Annotations
let counter: number;
// Inference: TypeScript will infer the type the `counter` to be `number`
let counter = 1;

Likewise, when you assign a function parameter a value, TypeScript infers the type of the parameter to the type of the default value. For example:

// TypeScript infers type of the `max` parameter to be `number`
const setCounter = (max = 100) => {
  // ...
}

Similarly, TypeScript infers the return type to the type of the return value:

const increment = (counter: number) => {
  return counter++;
}
// It is the same as:
const increment = (counter: number) : number => {
  return counter++;
}

The following shows other examples of type inference:

const items = [0, 1, null, 'Hi']; // (number | string)[]
const mixArr = [new Date(), new RegExp('\d+')]; // (RegExp | Date)[]
const increase = (counter: number, max = 100) => {
  return counter++;
}; // (counter: number, max?: number) => number

Contextual typing

TypeScript uses the locations of variables to infer their types. This mechanism is known as contextual typing. For example:

document.addEventListener('click', (event) => {
  console.log(event.button); // Valid
});

In this example, TypeScript knows that the event the parameter is an instance of MouseEvent because of the click event.

However, when you change the click event to the scroll the event, TypeScript will issue an error:

document.addEventListener('scroll', (event) => {
  console.log(event.button); // Compile error
}); // Property 'button' does not exist on type 'Event'.

TypeScript knows that the event in this case, is an instance of UIEvent, not a MouseEvent. And UIEvent does not have the button property, therefore, TypeScript throws an error.

Other examples about contextual typing

// Array members
const names = ['John', 'Jane', 'Peter', 'David', 'Mary']; // string[]
names.map(name => name.toUpperCase()); // (name: string) => string
// Type assertions
const myCanvas = document.getElementById('main-canvas') as HTMLCanvasElement;

Type inference vs Type annotations

Type inferenceType annotations
TypeScript guesses the typeYou explicitly tell TypeScript the type

What exactly is TypeScript any?

When you don’t explicitly annotate and TypeScript can’t infer exactly the type, that means you declare a variable without specifying a type, TypeScript assumes that you use the any type. This practice is called implicit typing. For example:

let result; // Variable 'result' implicitly has an 'any' type.

So, what exactly is any?

TypeScript any is a special type that you can use whenever you don’t want a particular value to cause type-checking errors. That means, the TypeScript compiler doesn’t complain or issue any error.

When a value is of type any, you can access any properties of it, call it like a function, assign it to (or from) a value of any type, or pretty much anything else that’s syntactically legal:

let obj: any = { x: 0 };
// None of the following lines of code will throw compiler errors.
// Using `any` disables all further type checking, and it is assumed 
// you know the environment better than TypeScript.
obj.foo();
obj();
obj.bar = 100;
obj = 'hello';
const n: number = obj;

Looking back at an easier to understand any:

  • A special type
  • Skip/Disable type-checking
  • TypeScript doesn’t complain any or issue any error
  • Default implicit typing is any.

Note that to disable implicit typing to the any type, you change the noImplicitAny option in the tsconfig.json file to true. Read more noImplicitAny

Why does TypeScript provide any type?

As described above, while TypeScript is a type checker, any type tell TypeScript to skip/disable type-checking.

Whether TypeScript has made a mistake here and why it provides any type?

In fact, sometimes the developer can’t determine the type of value or can’t determine the return value from the 3rd party. Most of cases they use any the type or use implicit typing as any. So they seem to think that TypeScript provides any to do those things.

So, is that the root reason that TypeScript provides any?

Actually, I think there is a more compelling reason for TypeScript providing any that the any type provides you with a way to work with the existing JavaScript codebase. It allows you to gradually opt-in and opt out of type checking during compilation. Therefore, you can use the any type for migrating a JavaScript project over to TypeScript.

Conclusion

TypeScript is a Type checker layer.

The TypeScript any type allows you to store a value of any type. It instructs the compiler to skip type-checking.

Use the any type to store a value when you migrate a JavaScript project over to a TypeScript project.

In the next blog, I will show you more about the harmful effects of any and how to avoid them.

Hope you like it! See you in the next blog!

Related Blog

Blog item

Anh test category 1705

Anh test category 1705 long nameeee category

Anh test category Anh test category Anh test category Anh test category Anh test category

+10

  • ANh test long name category ANh test long name category ANh test long name category
  • Hoa Test Category 1
  • Hoa Test Category 2
  • Hoa Test Category 3
  • Hoa Test Category 4
  • Hoa Test Category 5
  • Hoa Test Category quick update coloe
  • Our success stories
  • Tech news
  • Viet test

A Better Way To Use Services In React Application Anh test slug

Sometimes you have/want to create and use a service in your application for the DRY principle. But do you know exactly what is a service? And what is the best way to use services in React applications? Hi everyone! It's nice to meet you again in React related series. In the previous article, we discussed about effective state management in React, we learned about Context: what is it? when to use it? One of the use cases is using a context to share a collection of services through the components tree, but what kind of things can be called a service? And how is it integrated into React application? Let's discover the following sections: What is a Service? Service is just a group of helper functions that handle something particularly and can be reused across application, for example: Authentication Service that includes authentication status checking, signing in, signing out, getting user info …Http Service that handles request header, request method, request body … How to use? There are different kinds of implementation and usage, I just provide my favorite one that follows Angular module/services provider concepts. Create a service A service is a JavaScript regular class, nothing related to React. export default class ApiService { constructor() {} _setInterceptors() {} _handleResponse_() {} _handleError_() {} get() {} post() {} put() {} delete() {} } export default class AuthService { constructor() {} isAuthenticated() {} getUserInfo() {} signIn() {} signOut() {} } Create a Context Create a context with provider and pass services as props. import { createContext, useState } from 'react'; import { ApiService, AuthService } from '@services'; const services = { apiService: new ApiService(), authService: new AuthService() }; const AppContext = createContext(); const { Provider } = AppContext; const AppProvider = ({ children }) => { return <Provider value={{ services }}>{children}</Provider>; }; export { AppContext, AppProvider } Use a context Place a context provider at an appropriate scope, all consumers should be wrapped in it. import { AppProvider } from './context/AppContext'; import ComponentA from './components/ComponentA' const App = () => { return ( <AppProvider> <div className="app"> <ComponentA /> </div> </AppProvider> ); }; export default App; Inside a child component, use React hooks useContext to access services as a context value. import { useContext, useEffect } from 'react'; import { AppContext } from '../context/AppContext'; const ChildComponent = () => { const { services: { apiService, authService } } = useContext(AppContext); useEffect(() => { if (authService.isAuthenticated()) { apiService.get(); } }, []); return <></>; } export default ComponentA; Above are simple steps to integrate services with context. But it would be complicated in the actual work. Consider organizing context with approriate level/scope. My recommendation is to have two kinds of service contexts in your application: App Services Context to put all singleton services. Bootstrap it once at root, so only one instance for each is created while having them shared over the component tree.For others, create separate contexts and use them anywhere you want and whenever you need. Alternatives Service is not the only one way to deal with reusable code, it depends on what you intend to do, highly recommend to: Use a custom hook, if you want to do reusable logic and hook into a state.Use a Higher-order component, if you want to do the same logic and then render UI differently. Reference Does React Context replace React Redux?React RetiX - another approach to state management Author: Vi Nguyen

17/11/2023

1.68k

Vix Nguyen

Anh test category 1705

+12

  • Anh test category 1705 long nameeee category
  • Anh test category Anh test category Anh test category Anh test category Anh test category
  • ANh test long name category ANh test long name category ANh test long name category
  • Hoa Test Category 1
  • Hoa Test Category 2
  • Hoa Test Category 3
  • Hoa Test Category 4
  • Hoa Test Category 5
  • Hoa Test Category quick update coloe
  • Our success stories
  • Tech news
  • Viet test

A Better Way To Use Services In React Application Anh test slug

17/11/2023

1.68k

Vix Nguyen

Anh test category 1705 long nameeee category

ANh test long name category ANh test long name category ANh test long name category

Hoa Test Category 2

+6

  • Hoa Test Category 3
  • Hoa Test Category 4
  • Hoa Test Category 5
  • How-to
  • Our success stories
  • Tech news

The Recipe for a Perfect Shopify Store

We started by finishing the UI/UX of the storefront. This task was relatively easy; to stick with the gourmet kitchen theme, we were just slicing onions and cracking eggs. We implemented most of the UI/UX using Shopify Plus tools and received the desired images and themes from the client. We were able to use PageFly, one of Shopify’s public apps, to create the store’s landing page with ease. There is no reason to go to all the extra effort to build an app from scratch if a perfectly acceptable one already exists; sometimes canned tomatoes are better for the recipe than fresh ones. Although this part of the project was not the most labor-intensive, it was incredibly valuable. After all, the beautiful UI/UX is what our end users see when they make a purchase, so it requires extra attention. Makuake has a unique way of presenting its products on its Shopify Plus-powered store. Users can search for their favorite products by filtering by features or special tags attached to each product. Users can also search for the most recently added products, which is especially helpful for repeat customers of the Makuake store who want to keep up with the latest gadgets and inventions. A Dash of Spice: Shopify Custom Solutions While the UI/UX was built using available Shopify tools, there was one particular challenge that could not be solved with those tools alone. Makuake Store is a wonderful platform that supports entrepreneurship. It gives people a way to sell their unique creations, including craft spirits and alcohol. However, like most parts of the world, Japan has a legal drinking age (20 and up). Therefore, Makuake Store needed a way to distinguish between age-restricted products and normal products.

20/09/2023

3.03k

Anh test category 1705 long nameeee category

+8

  • ANh test long name category ANh test long name category ANh test long name category
  • Hoa Test Category 2
  • Hoa Test Category 3
  • Hoa Test Category 4
  • Hoa Test Category 5
  • How-to
  • Our success stories
  • Tech news

The Recipe for a Perfect Shopify Store

20/09/2023

3.03k

Hoa Test Category quick update coloe

+0

    Offline-to-Online Commerce with Shopify Plus

    Enterprises are using Shopify Plus to sell directly to their consumers because, let’s face it, most of us don’t like going to the store anymore. One of our clients decided to take some of their more unique products and start selling them online using newly integrated Shopify stores. It seems that Offline-to-Online commerce is an inevitable transformation in this era. Selling Directly to Consumers With Ecommerce You’ve probably been to a supermarket or drugstore and bought toothpaste. If not toothpaste, you may have bought soap or laundry detergent. If you haven’t gone to a brick-and-mortar store to buy any of these consumer goods, which can be found on shelves all over the world, then you’re way ahead of the game (or in desperate need of some soap).  Most people use these consumer products on a daily basis. When they run out of what they use, they can easily buy more at the nearest store. Unless they’ve pledged undying loyalty to a single brand, they’re likely to walk down the aisle and compare multiple products side by side on the shelf. This is the traditional way to shop for these types of products. But some products require special treatment. They’re not like all the other products, so they don’t belong on the shelf next to them. They are branded and marketed more carefully. Not to wholesalers and retailers, but directly to consumers.  But how does a large company, known only as a large company, with consumer goods on shelves everywhere, differentiate itself? One of our clients decided to launch Shopify stores to sell a few select products directly to consumers. 

    20/09/2023

    1.85k

    A123 author author author author

    Hoa Test Category quick update coloe

    +0

      Offline-to-Online Commerce with Shopify Plus

      20/09/2023

      1.85k

      A123 author author author author

      Anh test category 1705

      Hoa Test Category 1

      Hoa Test Category quick update coloe

      +2

      • Our success stories
      • Tech news

      OTT Streaming Platforms: Choose the Right Service for Your Needs

      In today’s digital landscape, Over-the-Top (OTT) streaming platforms have revolutionized the way content creators and producers deliver their content to audiences around the world. With the rise of OTT technology, the traditional broadcasting model has taken a backseat, allowing creators to reach viewers directly through the internet. This article aims to guide content creators and producers in selecting the ideal OTT streaming platform by dissecting crucial factors that influence this decision. OTT Streaming Understanding OTT Streaming Platforms What is OTT Technology? Over-the-Top streaming refers to the delivery of video and audio content over the internet, bypassing the need for traditional cable or satellite TV. This technology has gained substantial traction, with a staggering 48% year-over-year growth in OTT video consumption globally, showcasing the increasing preference for on-demand and personalized content experiences. How OTT streaming platforms work OTT platforms utilize the internet to transmit content to viewers’ devices, ensuring flexibility in content consumption. These platforms offer a diverse range of content, from movies and TV shows to live sports events and original series. One notable example is Netflix, which accounts for a remarkable 20% of the global downstream internet traffic. Step 1: One notable example is Netflix, which accounts for a remarkable 20% of the global downstream internet traffic. Step 2: One notable example is Netflix, which accounts for a remarkable 20% of the global downstream internet traffic. 私はほあです。🌻

      14/09/2023

      2.93k

      In today’s digital landscape, Over-the-Top (OTT) streaming platforms have revolutionized the way content creators and producers deliver their content to audiences around the world

      Anh test category 1705

      +4

      • Hoa Test Category 1
      • Hoa Test Category quick update coloe
      • Our success stories
      • Tech news

      OTT Streaming Platforms: Choose the Right Service for Your Needs

      14/09/2023

      2.93k

      In today’s digital landscape, Over-the-Top (OTT) streaming platforms have revolutionized the way content creators and producers deliver their content to audiences around the world

      Customize software background

      Want to customize a software for your business?

      Meet with us! Schedule a meeting with us!
      This site is registered on wpml.org as a development site. Switch to a production site key to remove this banner.