Header image

Tech news

TypeScript And “Any” Type

07/09/2022

293

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

Online-Food-Ordering-Systems

Knowledge

+0

    Exploring 7 Top Online Food Ordering Systems for Small Businesses

    After the Covid-19 pandemic, the convenience of online food ordering has become blatant for both consumers and businesses. SMEs, including independent restaurants and food establishments, are seeking for online ordering systems to expand their reach and boost sales. In this article, we'll explore seven popular online food ordering systems tailored for SMEs. With a jumble of options available, it's essential for SMEs to choose the right online food ordering system that aligns with their specific needs and budget. Hopefully, this article may help in making the right decision. Top online food ordering systems for SMEs What is online food ordering system? Online food ordering system is a digital platform that enables customers to buy food online. Some common features include browse menus, select dishes, customize order & delivery, and payment. On the other side, restaurant owners can easily manage and serve their customers accordingly. Though the list of feature may vary from each system to another, these are some key components of a typical food ordering system: Menu ManagementOrder PlacementPayment ProcessingOrder FulfillmentOrder TrackingCustomer AccountsFeedback and ReviewsAnalytics and Reporting We will dig deeper into each component in the upcoming blogs. Why using online food ordering system? With the dominance of food ordering services like ShopeeFood or GrabFood and its undeniable advantages, a question should be (or must be) asked: Why should SMEs use an independent ordering system? Lower commission rates Third-party delivery platforms often charge significant commission fees, which can eat into the profit margins of SMEs, particularly those with smaller-scale operations. Therefore, using other online food ordering systems that offer flat-rate pricing or commission-free options can be more cost-effective for SMEs. Less dependency Relying solely on third-party platforms for online food ordering can create a dependency on these platforms for business growth. By diversifying their online presence and using other ordering systems, SMEs can maintain more control over their online sales channels. Overall, third-party platforms remain a good choice for motorbike-friendly country. But who knows what the future holds? Top 7 online food ordering systems The availability of online food ordering systems has altered the way SMEs operate and interact with their customers. By leveraging the right online ordering platform, SMEs can streamline operations, improve customer experience, and drive sales growth. 1. Square Online Ordering Square Online Ordering is a feature of Square, a comprehensive platform that provides tools for businesses to manage various aspects of their operations, including point-of-sale (POS), payments, and online ordering. It seamlessly integrates with Square's comprehensive platform. With customizable ordering pages, menu management tools, and real-time order notifications, Square empowers SMEs to offer a branded and efficient online ordering experience to their customers. 2. Toast POS Toast POS is primarily a point-of-sale (POS) system designed specifically for restaurants. But it also offers online ordering capabilities as part of its platform. Overall, Toast POS offers a robust and integrated solution for restaurants looking to manage both in-person and online orders effectively. Toast enables SMEs to streamline operations and provide seamless offline-merge-online ordering options to their customers. 3. ChowNow ChowNow is a commission-free online ordering platform that caters to independent restaurants and small chains. With custom-branded ordering apps and websites, menu management tools, and CRM features, ChowNow empowers SMEs to create a personalized and cost-effective online ordering experience for their customers. 4. GloriaFood GloriaFood offers a free online ordering system for restaurants, cafes, and food trucks, making it an attractive option for budget-conscious SMEs. With customizable ordering widgets and integration with social media platforms, GloriaFood enables SMEs to easily set up and manage their online ordering presence. 5. Online Ordering System by Shopify Shopify's online ordering system allows SMEs to create their own branded online store with integrated ordering functionality. One main advantage of Shopify Online Ordering System is its integration and customization possibilities for Shopify stores. It's easy to choose an existing Shopify app and customize it to your tailored needs. Looking for a custom Shopify Online Ordering App? Maybe we can help! 6. Lightspeed Lightspeed offers a POS system with online ordering capabilities, designed to help small and mid-sized restaurants manage their operations more efficiently. With features such as menu management, order tracking, and integration with delivery services, Upserve enables SMEs to optimize their online ordering strategy and enhance customer satisfaction. 7. MenuDrive MenuDrive specializes in providing online ordering solutions for small and independent restaurants. With customizable online ordering websites, menu management tools, and integration with POS systems, MenuDrive empowers SMEs to create a branded and user-friendly online ordering experience for their customers. Which one is the best choice? In conclusion, while platforms like GrabFood and ShopeeFood can offer valuable exposure and access to a large customer base, SMEs should carefully weigh the pros and cons. Also, business owners should consider their specific business goals and needs before deciding which online food ordering systems to use. Ultimately, choosing the right platform or combination of platforms can help SMEs maximize their online sales and grow their business effectively.

    03/05/2024

    2

    Knowledge

    +0

      03/05/2024

      2

      Exploring 7 Top Online Food Ordering Systems for Small Businesses

      shopify app bridge

      Knowledge

      +0

        A to Z about Shopify App Bridge

        Howdy, tech fellows! It's Linh again for the SupremeTech's blog series. You may know this or not, but we do provide different solutions for Shopify-based businesses. That's why Shopify topics are among the most common you will see here. If interested in growing your business with Shopify/Shopify Plus, don't miss out. This article is all about Shopify App Bridge, from a non-technical point of view. What is Shopify App Bridge? Shopify App Bridge is a framework provided by Shopify that allows developers to create embedded applications within the Shopify ecosystem. In short, it helps you build, connect, publish apps that can be customized to your specific needs. It essentially serves as a bridge between third-party apps and the Shopify platform, enabling developers to seamlessly integrate their apps into the Shopify Admin interface. Why Shopify App Bridge? It is apparent that if you want to succeed on the platform, you must play by its rules. Shopify App Bridge allows you to add some custom tricks while keeping the rules. Here are some common features, offered by this framework, which make you manage your stores better with less effort. Embedded App Experiences: Merchants can access and interact with third-party app functionalities without leaving their Shopify dashboard.Enhancing Shopify Functionality: Adding custom features, automating tasks, or integrating with other services to streamline business operations.Customizing Shopify Admin Interface: Merchants can tailor their dashboard to their specific needs and preferences, improving efficiency and productivity.Cross-Platform Integration: It supports integration across various platforms, including web, mobile, and other third-party applications. This minimizes the effort spent when it comes to change in business strategy or platform migration.Improving User Experience: It eliminates the need for merchants to switch between different interfaces, leading to a more intuitive workflow. Therefore, the customers will be served faster.Enhanced Security: The bridge includes built-in security features to ensure that only authorized users and apps can access sensitive data within the Shopify ecosystem. In short, Shopify App Bridge offers tools for store customization beyond your wildest imagination. Is it exclusive for developers? Primarily, yes. For a highly-customized solution for large-scale business, maybe yes. However, its use extends to several other groups within the Shopify ecosystem: Shopify Merchants: Merchants who use the Shopify platform can benefit from apps built with Shopify App Bridge. These apps enhance the functionality of their Shopify stores, offering additional features, automating tasks, and improving the overall user experience.Shopify Partners: Shopify Partners, including agencies and freelancers, can utilize Shopify App Bridge to create custom solutions for their clients. By building embedded applications tailored to their clients' specific needs, Shopify Partners can provide added value and differentiate their services.Third-Party App Developers: Developers who create apps for the Shopify App Store can use Shopify App Bridge to enhance their app's integration with the Shopify platform. By embedding their apps directly within the Shopify Admin, they can provide a more seamless experience for merchants using their products.E-commerce Solution Providers: Companies that offer e-commerce solutions or services can leverage Shopify App Bridge to integrate their offerings with the Shopify platform. This allows them to provide their clients with a more comprehensive and integrated solution for managing their online stores. Key features of Shopify App Bridge Some of its primary features include: Embedded App Experiences: Shopify App Bridge enables developers to build apps that seamlessly integrate with the Shopify Admin interface. These embedded apps appear directly within the Shopify dashboard, providing merchants with a cohesive and intuitive user experience.UI Components: The framework provides a library of UI components that developers can use to create consistent and visually appealing interfaces for their embedded apps. These components maintain the look and feel of the Shopify platform, ensuring a seamless user experience.App Persistence: Apps built with Shopify App Bridge can maintain state and context across different pages and interactions within the Shopify Admin. This allows for a smoother user experience, as merchants can seamlessly navigate between different app functionalities without losing their progress.Cross-Platform Compatibility: Shopify App Bridge supports integration across various platforms, including web, mobile, and other third-party applications. This ensures that merchants can access embedded app experiences regardless of the device or platform they are using.Enhanced Security: The framework includes built-in security features to ensure that only authorized users and apps can access sensitive data within the Shopify ecosystem. This helps to protect merchants' information and maintain the integrity of the platform.App Bridge Action: App Bridge Action is a feature that allows developers to perform actions within Shopify Admin, such as navigating to specific pages or performing tasks, directly from their embedded apps. This helps to streamline workflows and improve efficiency for merchants.App Bridge APIs: Shopify App Bridge provides a set of APIs that developers can use to interact with the Shopify platform and access various functionalities, such as fetching data, managing orders, and updating settings. These APIs enable developers to build robust and feature-rich embedded applications. Conclusion In a nutshell, Shopify App Bridge is a game-changer for developers looking to jazz up Shopify stores. With its cool features like embedded apps, user-friendly UI bits, and the ability to keep things running smoothly even as you hop around the store, it's like the Swiss Army knife of Shopify customization. Plus, it's got your back on security, making sure only the right peeps get access to the good stuff. So, whether you're a developer dreaming up the next big thing or a merchant wanting to spruce up your online digs, Shopify App Bridge has got you covered, making your Shopify journey a breeze! If you are finding a way to boost up your business on Shopify, maybe we can help! Whether it's a Shopify custom development services for large-scale businesses or Shopify custom apps for individual request, we are confident to offer.

        22/04/2024

        69

        Knowledge

        +0

          22/04/2024

          69

          A to Z about Shopify App Bridge

          nativescript vs react native for cross-platform mobile development

          Knowledge

          +0

            NativeScript vs React Native: Comparing Cross-Platform Mobile Development Frameworks

            Hi tech fellows, the comparison series continues to dive in mobile development frameworks. This-week candidates call out NativeScript vs React Native. Both of them offer developers the ability to build apps that run seamlessly on both iOS and Android devices. So let's explore the similarities and differences in this article and make an informed decision when choosing a best fit for your project. Here are the six criteria to compare: Language and Development EnvironmentPerformance and User ExperienceUI Components and CustomizationDevelopment environmentCommunity and Ecosystem SupportPlatform Support and Integration Language and Development Environment NativeScript allows developers to write applications using JavaScript or TypeScript. It provides access to native APIs using JavaScript. React Native uses JavaScript and React, a popular JavaScript library for building user interfaces. Developers write components in JavaScript which are then compiled to native code. Both NativeScript and React Native empower developers to build cross-platform mobile applications using popular programming languages. NativeScript supports JavaScript and TypeScript, while React Native utilizes JavaScript and the React library. This means developers can leverage their existing skills and knowledge to kickstart their projects. Performance and User Experience NativeScript apps are compiled to native code, which generally provides better performance compared to hybrid frameworks. However, there might be some overhead due to the bridge between JavaScript and native code. React Native also compiles down to native code, but it uses a JavaScript bridge to communicate with native components, which might introduce some performance overhead. UI Components and Customization NativeScript provides UI components that map directly to native components, allowing for a truly native look and feel. It provides a large set of UI components out of the box. React Native also provides access to native UI components, but its component library might not cover all native features. However, it offers a vast ecosystem of third-party libraries and components. Development Environment NativeScript can be used with various development environments including Visual Studio Code, WebStorm, and others. It provides a CLI for project setup and management. React Native has a strong community and excellent tooling support. It comes with tools like Expo and React Native CLI for project setup and management. Community and Ecosystem NativeScript has a smaller community compared to React Native but still has a vibrant ecosystem with plugins and community support. React Native has a large and active community, which means more resources, tutorials, and third-party libraries available. While React Native boasts a larger community and ecosystem compared to NativeScript, both frameworks benefit from active developer communities and extensive documentation. This means you'll have access to resources, tutorials, and support channels to help you overcome challenges and streamline your development process. Whether you're a seasoned developer or just starting, the wealth of resources available for both frameworks ensures you're never alone on your development journey. Platform Support and Integration NativeScript supports iOS and Android platforms. It also provides some level of support for building web applications. React Native primarily targets iOS and Android platforms, but with the help of libraries like React Native Web, it's possible to target web browsers as well. Additionally, both frameworks offer mechanisms for integrating with native code when necessary, enabling you to access platform-specific features and functionalities. Whether you're targeting a specific platform or aiming for broad compatibility, both NativeScript and React Native provide the tools you need to succeed. NativeScript vs React Native: What should you choose? In conclusion, both NativeScript and React Native offer compelling solutions for cross-platform mobile app development. While NativeScript provides a more native approach with direct access to native APIs and UI components, React Native offers a familiar development experience with its use of JavaScript and React. Ultimately, the choice between NativeScript and React Native depends on your specific project requirements, familiarity with the respective technologies, and personal preferences. Whichever framework you choose, you can rest assured knowing that you're equipped with powerful tools and a supportive community to help you bring your mobile app ideas to life. Or if you need an expert to guide you through, we are here to help! Book a free consultation with us and share your pain-points. Thanks for reading! See you in the next article!

            03/04/2024

            162

            Knowledge

            +0

              03/04/2024

              162

              NativeScript vs React Native: Comparing Cross-Platform Mobile Development Frameworks

              OTT App development

              Tech news

              +0

                OTT App Development: Navigating The Common Revenue Models

                As Over-The-Top OTT app development reshapes media consumption, understanding its revenue landscape is crucial. Explore the intricacies of OTT app revenue models, including subscription-based, advertising-based, and transactional approaches. Discover how technological advancements, like AI and secure payment gateways, are impacting revenue generation. Learn how to overcome challenges and maximize profits in this dynamic industry. Overview of OTT Apps Development Over-The-Top (OTT) app development is revolutionizing the way we consume media and entertainment. These apps, which deliver video content directly over the internet, bypass traditional distribution channels such as cable or satellite TV. They are growing in popularity due to their convenience, as they allow users to access a vast variety of content anytime, anywhere, on any device. Additionally, they offer innovative monetization strategies that are reshaping the revenue landscape of the entertainment industry. Understanding the Revenue Landscape The revenue landscape for OTT apps is complex and multi-faceted. It entails a variety of revenue models, each with its own unique advantages and challenges. These models determine how the apps generate income, whether it's through user subscriptions, advertising, or pay-per-view transactions. Understanding these models is essential for any business looking to thrive in the OTT space. OTTs app development - Revenue Landscape Key Revenue Models for OTT Apps Custom OTT platforms primarily utilize three revenue models: subscription-based, advertising-based, and transactional models. Subscription-based Model The subscription-based business model is a popular choice in the world of Over-The-Top (OTT) applications. This model, which requires users to pay a subscription fee either monthly or yearly, provides access to a comprehensive library of content. By subscribing, users can enjoy a wide variety of content from different genres and formats, making it a one-stop solution for their entertainment needs. This model is beneficial for the service providers as well, as it guarantees a consistent revenue stream. This predictability of income allows these platforms to invest in acquiring new content, improving their services, and even producing their own original content. Major platforms like Netflix and Hulu use this model. They offer a diverse range of content including movies, TV series from various networks, and their own original productions. OTTs app development - SVOD model Advertising-based Model In the advertising-based model, users get to view the content for free. However, this content comes with advertisements in between. The money comes from these advertisements. Advertisers pay to display their ads within the content. YouTube is a great example of this model. It features content from users, music videos, and more. From a development viewpoint, this model needs strong ad-serving technologies. It also requires algorithms to ensure ads are placed at the right spots. These measures help to increase ad views and clicks, leading to higher revenue. OTTs app development - AVOD model Transactional Model The transactional or pay-per-view model is a revenue strategy in which users make payments for each piece of content they consume. This approach is prevalent on platforms like Amazon Prime, primarily for renting or buying individual movies. It's especially effective for offering premium or exclusive content that users are inclined to pay additional charges for. This model necessitates a reliable and secure payment gateway, along with a robust content delivery network to ensure seamless access to premium content. A well-structured database to manage individual user transactions and preferences is also crucial for personalized content delivery. Challenges in Navigating the Revenue Landscape - Maximizing profit In the OTT app development world, making money can be a big challenge. Developers need to set the right prices to keep users and stay profitable. They also have to deal with content rights, which can be complicated, especially when dealing with different countries. The OTT app development market is also getting more competitive with new players entering all the time. To maximize revenue, it's important to know your audience, choose the right revenue model, and keep improving your app. Staying up to date with market trends and user preferences is also vital. Furthermore, using analytics to understand user behavior and preferences can help in creating personalized experiences and content suggestions, which can increase user engagement and keep them coming back. OTTs app development The Impact of Technological Advancements on OTT Revenue Technological advancements have a profound impact on the OTT revenue landscape. For instance, the advent of artificial intelligence (AI) and machine learning (ML) technologies has enabled OTT platforms to offer personalized content and advertisements, leading to increased user engagement and thereby, higher revenue. Also, the development of secure payment gateways has made transactions more straightforward and safer, encouraging more users to opt for premium content or subscriptions. Conclusion OTT apps have transformed the way we consume media and entertainment, offering users an unprecedented level of convenience and choice. By understanding the revenue landscape and adopting the right strategies, businesses can tap into the immense potential of OTT apps and achieve sustainable growth. Ready to revolutionize your media business and maximize revenue? Explore our comprehensive OTT solution tailored to meet your needs. With subscription-based, advertising-based, and transactional models integrated seamlessly, along with cutting-edge technologies to enhance user engagement and monetization, our OTT solution empowers you to navigate the revenue landscape effectively. Take the next step towards success in the OTT industry today!

                27/03/2024

                148

                Tech news

                +0

                  27/03/2024

                  148

                  OTT App Development: Navigating The Common Revenue Models

                  Post banner imagePost banner image
                  Customize software background

                  Want to customize a software for your business?

                  Meet with us! Schedule a meeting with us!