Header image

Tech news

TypeScript And “Any” Type

07/09/2022

99

Table of contents

  • What is TypeScript?
  • Basic typing
  • What is TypeScript any type?
  • Why does TypeScript provide any?
TypeScript And “Any” Type

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

typescript-javascript
  • 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!

Reference

Author: Anh Nguyen

Related Blog

satellite project for healthcare management system

Success stories

+0

    A Satellite Project for Healthcare Management Systems

    In the ever-evolving landscape of healthcare, SupremeTech emerges as a beacon of innovation, dedicated to empowering healthcare centers and healthcare management systems. This journey unfolds through the art of creating satellite projects, commitment to deadlines, adaptability in action, and the extra mile with offshore development. Let's delve into how SupremeTech carefully designs each satellite project to prioritize value, precision, and adaptability in healthcare solutions. The Art of Creating Satellite Projects Understanding the need for scalability in healthcare management systems The healthcare landscape is ever-evolving, and SupremeTech has acknowledged the need for scalable solutions. In this segment, we explore the crucial role of scalability in healthcare management systems.  Healthcare Management System (CMS), which SupremeTech developed as an offshore development solution, offers you seamless access to update citizens' health information. This user-friendly platform empowers you to stay connected and informed. Moreover, our systems facilitate smooth communication between citizens and healthcare providers, enabling remote consultations and health ranking services. This not only enhances care accessibility, particularly for individuals in remote areas or with limited mobility but also elevates citizen engagement and satisfaction.Embracing citizen engagement and promoting self-care, our digitized healthcare management system instills a sense of empowerment and responsibility for personal health. Through easy-to-use interfaces and intuitive mobile applications, individuals can engage in activities that promote better health. From setting fitness goals, monitoring exercise routines, and tracking nutrition, to accessing educational resources and connecting with support communities, a digitized health management system empowers citizens to make informed decisions and adopt healthy lifestyle choices. SupremeTech's approach to create satellite projects from large-scale projects. SupremeTech's special skill is making big ideas into easy-to-handle projects. Explore how we extract satellite projects from large-scale initiatives, ensuring not just size but also adaptability and precision. Recognizing that an optimal Agile team size ranges between 7 to 10 individuals, we want to highlight that SupremeTech takes deliberate measures to imbue adaptability into each satellite project. This signifies that these projects are engineered to evolve, pivot, and effortlessly incorporate new features or modifications as necessary, guaranteeing a responsive and dynamic reaction to evolving requirements.  That's the reason why SupremeTech has decided to create a good satellite project with the Healthcare Management System (CMS) and application to adapt to new requests from clients who want to create a new health tracking system in a new city. Deadline Management: A Supreme Commitment Importance of meeting deadlines in healthcare projects. Time is a precious commodity in healthcare. The timely implementation of projects directly impacts everyone's healthcare. SupremeTech recognizes that delays can have far-reaching consequences, and meeting deadlines is not just a goal but a necessity. SupremeTech's strategies for effective project timeline management. SupremeTech makes projects that can change and adapt easily to fit different needs. We focus on making these projects precise and flexible to meet the ever-changing demands. Comprehensive Planning: The journey begins with meticulous planning. Before a project even starts, a comprehensive roadmap is laid out, detailing every milestone and task with our clients. This strategic planning allows for a clear understanding of the project scope, potential challenges, and the critical path to success.Clear Communication Channels: Communication is the key to effective project timeline management. SupremeTech establishes clear and transparent communication channels, both internally and with clients. This ensures that everyone involved is on the same page, minimizing misunderstandings and facilitating quick decision-making. Risk Management Strategies: Every project comes with inherent risks. SupremeTech, however, doesn't just identify risks; it proactively manages them. Robust risk management strategies are in place to anticipate and address potential challenges, preventing them from derailing the project timeline. Adaptability in Action In the intricate world of healthcare projects, where change is constant, SupremeTech orchestrates a seamless dance, showcasing the vital need for adaptability. As projects evolve, SupremeTech's flexibility shines through, effortlessly accommodating new requests and embracing change with unparalleled finesse. Clients witness a dynamic partner who not only keeps pace with evolving needs but actively thrives in the ever-shifting landscape of healthcare project execution. Benefits for All Explore the tangible benefits that SupremeTech's proactive approach brings to Public Health sectors, Healthcare centers, and Healthcare systems. From improved scalability to streamlined processes and enhanced employee engagement, discover how SupremeTech creates a positive impact for all. Offshore Development: The Extra Mile Dive into the technological backbone that supports SupremeTech's success. Learn how SupremeTech transcends geographical boundaries, bringing together global collaboration for unparalleled efficiency. Development systems and technologies Below are the resources and technologies we use to develop the services: Details of entrustment: Design, Implementation, Testing, Migration, Maintenance & Operation Platform: CMS, Native App Development language: PHP (Laravel), Kotlin, Swift  Let SupremeTech help you to start your healthcare management system now! As our journey concludes, embark on your adventure by visiting SupremeTech. Witness the culmination of expertise, dedication, and innovation. For a new beginning in healthcare management solutions, contact SupremeTech and be a part of a story that goes beyond success - a story of continual innovation and transformation in healthcare management. Don't wait, take the first step towards a more efficient and effective healthcare system today.

    06/12/2023

    4

    Success stories

    +0

      06/12/2023

      4

      A Satellite Project for Healthcare Management Systems

      line mini app to digital transform customer service

      Success stories

      +0

        LINE Mini App: Digital Transform Customer Service with Digital Point Cards

        SupremeTech has been on an impressive journey of building and developing, positively impacting customers. One of our recent and innovative projects involved meeting our client's request to launch digital point cards integrated in Line Mini App. These cards allow customers to accumulate points or make payments within their network of stores. Previously, our client used physical cards for this purpose. However, recognizing the potential of using digital means to encourage more transactions, they swiftly moved forward. Initiating suitable solutions for a traditional issue With a commitment to customer satisfaction and delivering the best app experience, we proved our capabilities in doing this project. Understanding the client's needs, we embarked on research to provide a viable solution for developing and maintaining a mobile application for issuing and managing digital point cards. The app enables users to effortlessly carry and use their point cards on their smartphones, with key features including card issuance, displaying corresponding barcodes, and generating one-time barcodes for transactions. Developing a Loyalty App on Line App: What Sets it Apart A unique requirement for this project was the development of a mini-app on the Line app. Line, a popular international communication and calling app developed by LINE Corporation, offers various gaming and platform applications for users' entertainment and interaction within a virtual environment. This was an entirely new platform for SupremeTech, and despite no prior experience, the team immediately dove into research. Developing the app on Line presented challenges such as limited customization options for interface and user experience, adherence to Line's regulations, and potential limitations or lack of support for specific features. Overcoming Challenges and Successfully Launching the Line Mini-App Despite these challenges, SupremeTech successfully completed the Line mini-app project. Leveraging the versatility of React and Node.js, the team maximized Line's API and SDK potential for seamless integration and interaction with Line App features. Additionally, research was conducted to combine with other systems for data retrieval. After six months of dedicated efforts, the Loyalty App on Line App was successfully released. Highlighted Features This mobile app can issue digital point cards by entering user information or linking with physical cards to display information as barcodes. Key features include: Card Issuance: Allows customers to issue digital point cards.Barcode Display: Displays corresponding barcodes for each digital point card.One-time Barcodes: Generates one-time barcodes for specific transactions or interactions. Contributing to the Business Ecosystem This technological solution significantly contributes to the current business ecosystem by optimizing customer loyalty programs. It encourages customer transactions across all business service points. The app seamlessly connects with customer data systems, ensuring a smooth experience for the business and its customers. If you want to modernize your business and enterprise ecosystem with a cutting-edge loyalty app, don't hesitate to contact SupremeTech. We're here to help your business thrive.

        05/12/2023

        10

        Success stories

        +0

          05/12/2023

          10

          LINE Mini App: Digital Transform Customer Service with Digital Point Cards

          shopify order tracking app for the food industry

          Success stories

          +0

            Shopify Order Tracking App for The Food Industry

            TakeOut is a Shopify application that allows restaurants and food industry businesses to streamline their takeout service. Instead of relying on a third-party application to sell and deliver food online, customers can order directly from the restaurant with this Shopify order tracking app. Sounds like a delicious way to increase profit engagement with customers! Almost everyone who lives in an urban area has had food delivered to them. Of course, there have always been a few more options when it comes to takeout. There's the stereotypical "Chinese takeout" that comes in a paper oyster shell tossed into a bag with disposable chopsticks and a handful of fortune cookies. If only one of those fortune cookies had told us about the possibilities of future food delivery and takeout! Today, all of your favorite foods are available for takeout or delivery.  Shopify Serves Small Restaurant Businesses The project began when a client approached us with the concept of giving small businesses a way to reduce their operating costs. Although there are many benefits to being listed on popular delivery and takeout websites and applications, but these benefits come at a financial cost. For some businesses, this is fine; just pay the fee and keep selling! However, some businesses prefer to keep these external costs to a minimum. Utilizing Shopify's Popularity in Japan In Japan, Shopify has become increasingly popular. Our partner client saw an opportunity to capitalize on this popularity and create an application that gives restaurants a choice. Now, Japanese restaurants can choose to sell their products through a well-known service or put more effort into developing their own brand and selling their food directly to hungry end users. TakeOut Functions for Foodies The first function of TakeOut is the call function. This allows customers to place a takeout order from the restaurant's Shopify website. The application shows where the food is in the pipeline, from the order being received, to being in the kitchen, to being ready for pickup. When the food is close to being ready, the application can send a push notification to notify the customer. If a client restaurant wants to add additional customization to the pipeline or takeout application, we can accommodate any request. Again, this is the beauty of Shopify: with a qualified team, the customization possibilities are nearly endless! User-friendliness is Delicious! Furthermore, adding the TakeOut application to a restaurant's Shopify is incredibly easy. In most cases, you won't need a development team at all. We've created a step-by-step guide on how to integrate the app into an existing Shopify store. All the restaurant owner has to do is follow the steps, then they're selling their deliciousness directly to customers. Similar to how customers might want to customize their food order, if there's something that needs to be changed, we can do the customization for the restaurant's Shopify.  TakeOut Challenges: Multiple Locations The project itself was not too difficult. A small team developed the application over the course of three months. SupremeTech had a lot of experience working with Shopify and our partner Fracta on other projects.   We worked seamlessly with our client partner. Our Japanese business analyst coordinated communication between the engineering team and Japanese stakeholders. However, despite our best efforts, there was one particular challenge that nearly tripped us up! Development projects rarely go by without some challenge or miscommunication. However, during the TakeOut project, we were able to adapt and complete the project on time. We worked under the assumption that the Shopify stores we were developing TakeOut for were stand-alone locations. We developed the app under without considering businesses with multiple locations. Due to Shopify's policy, this required some last-minute tinkering. Fortunately, we were able to power through the last minute adjustments. Sudden changes are common in our industry. Nonetheless, we learned valuable lesson about adapting when the client's specifications change.  Serving Customers With TakeOut TakeOut was a Shopify eCommerce application that we developed to help small businesses. We continue to work closely with our partner client to add new features to the app as the market dictates. To date, TakeOut's client restaurants and food lovers have praised its user-friendly interface. We're excited to see how the platform continues to change the way we do eCommerce in the future. Contact SupremeTech if you want the same Shopify order tracking app or any custom Shopify solutions. We make your business smarter and smoother!

            23/11/2023

            70

            Success stories

            +0

              23/11/2023

              70

              Shopify Order Tracking App for The Food Industry

              golang for devops

              How-To

              Knowledge

              Tech news

              +0

                Golang for DevOps: Empowering Infrastructure as Code and Automation

                In the realm of DevOps, efficiency, agility, and automation are paramount. This article explores how the Go programming language, often referred to as Golang, plays a significant role in DevOps by enabling infrastructure as code, automation scripts, and deployment tools. We will also discuss how Golang development services can support DevOps teams in achieving their goals. Understanding DevOps Before diving into Golang's role in DevOps, let's clarify what DevOps is all about. DevOps is a set of practices that aims to break down the traditional silos between development and IT operations teams. It promotes collaboration, communication, and automation to streamline software development and deployment processes. Infrastructure as Code with Golang Infrastructure as Code (IaC) is a cornerstone of DevOps, allowing infrastructure to be managed and provisioned using code. Golang is a powerful language for creating IaC because of its simplicity, efficiency, and excellent support for concurrent programming. Declarative IaC: Golang enables the creation of declarative IaC scripts, where you specify the desired state of your infrastructure. You can use tools like Terraform and Pulumi, which are written in Go, to define your infrastructure in a human-readable format. Golang's syntax is clean and easy to understand, making it an excellent choice for this purpose.Concurrency: DevOps often involves managing multiple resources and services concurrently. Golang's built-in support for concurrency with Goroutines and Channels ensures that you can manage your infrastructure efficiently. This is especially valuable when dealing with large-scale, distributed systems.Performance: Golang is known for its performance. When you need to apply changes to your infrastructure rapidly, Golang's speed can significantly reduce the time it takes to provision and manage resources, contributing to overall DevOps efficiency. Automation Scripts in Golang Automation is at the heart of DevOps, as it allows for repetitive tasks to be executed with precision and consistency. Golang's design makes it a perfect fit for writing automation scripts. Cross-platform Compatibility: Golang can compile code for multiple operating systems and architectures. This means that a single Golang script can run on various platforms, reducing the need to maintain separate scripts for different environments.Static Typing: Golang's static typing system provides robust error checking, helping to catch potential issues early in the development process. This feature is particularly beneficial when writing scripts that interact with critical systems.Rich Standard Library: Golang's standard library offers a wealth of packages for working with APIs, databases, networking, and more. DevOps professionals can leverage these packages to streamline the development of automation scripts.Ease of Deployment: Golang's ability to produce standalone binaries simplifies deployment. You don't need to worry about dependencies or runtime environments when distributing your scripts. Deployment Tools and Golang Development Services Deploying applications and services efficiently is a core aspect of DevOps. Golang can be a valuable ally in creating deployment tools that ensure smooth and reliable application delivery. Custom Deployment Pipelines: Golang allows DevOps teams to create custom deployment pipelines tailored to their specific requirements. You can build tools that handle everything from continuous integration to deployment, monitoring, and scaling.Integration with Containerization: Containers are a fundamental component of modern DevOps, and Golang is well-suited for creating container-related tools. Many container orchestration tools, like Kubernetes, are written in Golang, showcasing its capability in this area.Microservices Deployment: DevOps often involves the deployment of microservices. Golang's small binary size and efficient concurrency handling make it an excellent choice for managing and orchestrating microservices within a larger system. Support from Golang Development Services Golang development services provide valuable support to DevOps teams aiming to leverage the language for infrastructure as code, automation, and deployment. Here are some ways these services can assist: Consultation: Golang development services can offer expert advice and guidance on the best practices for using Golang in your DevOps processes. They can help you determine the most suitable tools and frameworks for your specific needs.Custom Tooling: Golang development services can create custom tools and scripts tailored to your infrastructure and deployment requirements. This ensures that your DevOps processes are as efficient as possible.Integration: Golang development services can integrate Golang-based tools with your existing systems, ensuring a seamless transition and coexistence with your current infrastructure.Maintenance and Support: DevOps is an ongoing process, and Golang development services can provide ongoing maintenance and support for the tools and scripts they develop, helping you keep your DevOps pipelines running smoothly. Conclusion Golang's simplicity, efficiency, and robust support for concurrent programming make it a valuable asset for DevOps teams looking to implement infrastructure as code, automation, and deployment processes. The language's capabilities, combined with the support of Golang development services, enable DevOps professionals to streamline their workflows, achieve higher efficiency, and meet the demands of modern, agile software development and deployment. Whether you are creating infrastructure as code, automation scripts, or deployment tools, Golang is a versatile and powerful choice in the DevOps toolbox. Contact us for your tailored Golang development services.

                17/11/2023

                89

                How-To

                +2

                • Knowledge
                • Tech news

                17/11/2023

                89

                Golang for DevOps: Empowering Infrastructure as Code and Automation

                Post banner imagePost banner image
                Customize software background

                Want to customize a software for your business?