Header image

TypeScript – How To Avoid “Any”?

26/09/2022

1.08k

  • The harmful effects of any
  • Avoiding any
TypeScript - How To Avoid "Any"?

How to avoid any?

In the previous blog – Typescript and “any” type, I introduced TypeScript and what exactly is any type.

In this blog, I’d like to show more about the harmful effects when using any and introduce some built-in types, features and customs types that you can use to avoid any.

The harmful effects of any

While TypeScript is a type checker, any type tells TypeScript to skip/disable type-checking. On the other hand, due to the nature of JavaScript, in some cases providing accurate types isn’t a simple task. In such situations, programmers are tempted to use any.

In most situations using or implicit any – a type that allows to store anything and skip type checkers, programmers can’t guarantee what type the value is stored and how it will be used. Furthermore, when the code is executed at runtime, errors may occur even though they were not warned before. For example:

let result; // Variable 'result' implicitly has an 'any' type.
result = 10.123; // Number is stored at 'result'

console.log(result.toFixed()); // `toFixed()` is a method of `number`

result.willExist(); // `willExist()` isn't a method of `number`, but no errors appear.

Because of that, the use of any is something that should be minimized as much as possible, to ensure the source code does not encounter any errors.

Avoiding any

Based on the basics of TypeScript and Everyday Types, in this blog, I’ll be sharing what I learned and used to write code without any.

Type aliases & Interfaces

A type alias is exactly a name for any type, you can actually use a type alias to give a name to any type at all, not just an object type. For example:

// Type alias
type Point = {
  x: number,
  y: number
};

type ID = number | string;

An interface declaration is another way to name an object type:

// Interface
interface IPoint {
  x: number,
  y: number
};

Differences between Type Aliases and Interfaces:

// Override
type Point = { // TypeError: Duplicate identifier 'Point'.
  a: string
};
interface IPoint {
  a: string
};

Union & Literal types

A union type is a type formed from two or more other types, representing values that may be any one of those types.

// Union types
let anyNumber: string | number;

// Usage
anyNumber = '123';
anyNumber = 123;
anyNumber = true; // TypeError: Type 'boolean' is not assignable to type 'string | number'.

In addition to the general types of string and number, you can refer to specific value of strings and numbers.
By combining literals into unions, you can express a much more useful concept. For example:

// Literal types
let direction: 'top' | 'left' | 'right' | 'bottom';

direction = 'top';
direction = 'top-right'; // TypeError: Type '"top-right"' is not assignable to type '"top" | "left" | "right" | "bottom"'

Type assertions

Sometimes you will have information about the type of a value that TypeScript can’t know about.

For example, if you’re using document.getElementById, TypeScript only knows that this will return some kind of HTMLElement, but you might know that your page will always have an HTMLCanvasElement with a given ID.

In this situation, you can use a type assertion to specify a more specific type:

// Type assertions
const myCanvas = document.getElementById('main-canvas') as HTMLCanvasElement;

Generics

// Example
const getRandomNumber = (items: number[]): number => {
  let randomIndex = Math.floor(Math.random() * items.length);
  return items[randomIndex];
};
const getRandomString = (items: string[]): string => {
  let randomIndex = Math.floor(Math.random() * items.length);
  return items[randomIndex];
};

// Generics function
const getRandomGeneric = <T>(items: T[]): T => {
  let randomIndex = Math.floor(Math.random() * items.length);
  return items[randomIndex];
};

// Usage
const teams: string[] = ['frontend', 'ios', 'android'];
const numbers: number[] = [1, 2, 3, 4, 5, 6, 7, 9, 10];

const randomResult1 = getRandomGeneric<string>(teams);
const randomResult2 = getRandomGeneric<number>(numbers);

In the example above, the getRandomGeneric is the generic identity function that worked over a range of types.

The type of generic functions is just like those of non-generic functions, with the type parameters listed first, similarly to function declarations:

const identity = <Type>(param: Type): Type => {
  return param;
};

When calling identity a function, you now will also need to specify the type of param that the function will use.

The detail above just Generic identity functions, you can read more generics Generic link

Unknown

unknown is what should be used when you don’t know a proper type of object. Unlike any, it doesn’t let you do any operations on a value until you know its type (skip/disable type-checker).

When you unknow something, you need to check before executing. For example:

const invokeAnything = (callback: unknown): void => {
  if (typeof callback === 'function') {
    callback();
  }
  if (typeof callback === 'number') {
    console.log(callback);
  }
  if (typeof callback === 'string') {
    console.log(callback.toUpperCase());
  }
};

// Usage
invokeAnything('typescript'); // Result: TYPESCRIPT

Record for basic object

Probably, nearly every JavaScript developer at some time has used an object as a map-like collection. However, with strict types, it may not be that obvious how to type this. So, you may use interface, but this way you can’t add anything to the object. Then, you need to think about using Record.

The definition:

type Record<K extends keyof any, T> = {
  [P in K]: T;
};

And the usage:

// Usage
const dict: Record<string, number> = {};
dict.a = 1;
dict.b = 'a'; // TypeError: "a" is not assignable to type number

let obj: Record<string, number>;
obj = {
  a: 1,
  b: 2
};

As you can see, it means that the developer can enter any key, but the value has to be of a specific type.

Conclusion

The TypeScript compiler is so powerful. There are so many things we can do with it.

any type can be avoided with more advanced technics such as interface, type intersection, and the use of generics, etc.

Hope you like it! Enjoy TypeScript and make the code without any!

Author: Anh Nguyen

Related Blog

prd-thumb-draft-product

Software Development

+0

    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! 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 that adds rules about how different kinds of values can be used. Runtime Behavior TypeScript is also a programming language that preserves JavaScript's runtime behavior. This means that if you move code from JavaScript to TypeScript, it is guaranteed to run the same way, even if TypeScript thinks 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 languageA superset of JavaScriptPreserver the runtime behavior of JavaScriptType 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 of 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 annotationsTypeScript 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 particular 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 errors. 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 or issue any errors.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. Why does TypeScript provide any type? As described above, while TypeScript is a type checker, any type tells 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. In most cases they use any type or 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 TypeScript handbookTypeScript tutorial Author: Anh Nguyen

    07/09/2022

    728

    Software Development

    +0

      TypeScript And “Any” Type

      07/09/2022

      728

      ionic vs react native

      Software Development

      +0

        Ionic vs. React Native: A Comprehensive Comparison

        Ionic vs. React Native is a common debate when choosing a framework for cross-platform app development. Both frameworks allow developers to create apps for multiple platforms from a single codebase. However, they take different approaches and excel in different scenarios. Here’s a detailed comparison. Check out for more comparisons like this with React Native React Native vs. Kotlin Platform Native Script vs. React Native The origin of Ionic Framework Ionic Framework was first released in 2013 by Max Lynch, Ben Sperry, and Adam Bradley, founders of the software company Drifty Co., based in Madison, Wisconsin, USA. What's the idea behind Ionic? The creators of Ionic saw a need for a tool that could simplify the development of hybrid mobile apps. At the time, building apps for multiple platforms like iOS and Android required separate codebases, which was time-consuming and resource-intensive. Therefore, the goal was to create a framework that allowed developers to use web technologies—HTML, CSS, and JavaScript—to build apps that could run on multiple platforms with a single codebase. Its release and evolution over time The first version of Ionic was released in 2013 and was built on top of AngularJS. It leveraged Apache Cordova (formerly PhoneGap) to package web apps into native containers, allowing access to device features like cameras and GPS. 2016: With the rise of Angular 2, the team rebuilt Ionic to work with modern Angular. The renovation improved performance and functionality. 2018: Ionic introduced Ionic 4, which decoupled the framework from Angular, making it compatible with other frameworks like React, Vue, or even plain JavaScript. 2020: The company developed Capacitor, a modern alternative to Cordova. It provides better native integrations and supports Progressive Web Apps (PWAs) seamlessly. Key innovations of Ionic First of all, Ionic popularized the use of web components for building mobile apps. In addition, it focused on design consistency, offering pre-built UI components that mimic native app designs on iOS and Android. Thirdly, its integration with modern frameworks (React, Vue) made it appealing to a broader developer audience. Today, Ionic remains a significant player in the hybrid app development space. It's an optimal choice for projects prioritizing simplicity, web compatibility, and fast development cycles. It has a robust ecosystem with tools like Ionic Studio. Ionic Studio is a development environment for building Ionic apps. The origin of React Native React Native originated at Facebook in 2013 as an internal project to solve challenges in mobile app development. Its public release followed in March 2015 at Facebook’s developer conference, F8. Starting from the problem of scaling mobile development In the early 2010s, Facebook faced a significant challenge in scaling its mobile app development. They were maintaining separate native apps for iOS and Android. It made up duplicate effort and slowed down development cycles. Additionally, their initial solution—a hybrid app built with HTML5—failed to deliver the performance and user experience of native apps. This failure prompted Facebook to seek a new approach. The introduction of React for Mobile React Native was inspired by the success of React, Facebook’s JavaScript library for building user interfaces, introduced in 2013. React allowed developers to create fast, interactive UIs for the web using a declarative programming model. The key innovation was enabling JavaScript to control native UI components instead of relying on WebView rendering. Its adoption and growth React Native quickly gained popularity due to its: Single codebase for iOS and Android.Performance comparable to native apps.Familiarity for web developers already using React.Active community and support from Facebook. Prominent companies like Instagram, Airbnb, and Walmart adopted React Native early on for their apps. Today, React Native remains a leading framework for cross-platform app development. While it has faced competition from newer frameworks like Flutter, it continues to evolve with strong community support and regular updates from Meta (formerly Facebook). Ionic vs. React Native: What's the key differences? Core Technology and Approach React Native Uses JavaScript and React to build mobile apps.Renders components using native APIs, resulting in apps that feel closer to native experiences.Follows a “native-first” approach, meaning the UI and performance mimic native apps. Ionic Uses HTML, CSS, and JavaScript with frameworks like Angular, React, or Vue.Builds apps as Progressive Web Apps (PWAs) or hybrid mobile apps.Renders UI components in a WebView instead of native APIs. Performance React Native: Better performance for apps that require complex animations or heavy computations.Direct communication with native modules reduces lag, making it suitable for performance-intensive apps. Ionic: Performance depends on the capabilities of the WebView.Works well for apps with simpler UI and functionality, but may struggle with intensive tasks or animations. User Interface (UI) React Native: Leverages native components, resulting in a UI that feels consistent with the platform (e.g., iOS or Android).Offers flexibility to customize designs to match platform guidelines. Ionic: Uses a single, web-based design system that runs consistently across all platforms.While flexible, it may not perfectly match the native look and feel of iOS or Android apps. Development Experience React Native: Ideal for teams familiar with React and JavaScript.Offers tools like Hot Reloading, making development faster.Requires setting up native environments (Xcode, Android Studio), which can be complex for beginners. Ionic: Easier to get started for web developers, as it uses familiar web technologies (HTML, CSS, JavaScript).Faster setup without needing native development environments initially. Ecosystem and Plugins React Native: Extensive library of third-party packages and community-driven plugins.Can access native features directly but may require writing custom native modules for some functionalities. Ionic: Has a wide range of plugins via Capacitor or Cordova for accessing native features.Some plugins may have limitations in terms of performance or compatibility compared to native implementations. Conclusion: Which One to Choose? Choose React Native if:You want high performance and a native-like user experience.Your app involves complex interactions, animations, or heavy processing.You’re building an app specifically for mobile platforms.Choose Ionic if:You need a simple app that works across mobile, web, and desktop.You have a team of web developers familiar with HTML, CSS, and JavaScript.You’re on a tight budget and want to maximize code reusability. Both frameworks are excellent in their own right. Your choice depends on your project’s specific needs, the skill set of your development team, and your long-term goals.

        19/11/2024

        18

        Linh Le

        Software Development

        +0

          Ionic vs. React Native: A Comprehensive Comparison

          19/11/2024

          18

          Linh Le

          inter bee 2024

          OTT Streaming

          Our success stories

          +0

            SupremeTech & Enlyt Showcase CloudTV Streaming Solution at Inter BEE 2024

            SupremeTech, along with our partner Enlyt, is excited to present CloudTV, our advanced streaming platform, at Inter BEE 2024. This event is a great chance for us to connect with other professionals in media and technology. We aim to show how CloudTV can help businesses deliver smooth and high-quality streaming to their audiences. Through CloudTV, we’re ready to make streaming easier and more accessible. Inter BEE 2024 is held between November 13 and 15, 2024. Let's join us! About Inter BEE 2024 Inter BEE, or International Broadcast Equipment Exhibition, is one of Japan’s biggest media and tech events. It takes place at Makuhari Messe and marks its significant 60th year in 2024. This exhibition gathers thousands of visitors and exhibitors from around the world. They include professionals from video, audio, and digital media industries. Over 1,000 exhibitors are part of this year’s event, and they bring their latest tools and ideas in content creation, delivery, and audience engagement. Inter BEE also includes unique interactive spaces, like INTER BEE CINEMA, which focuses on new film production tools, and the INTER BEE AWARD, which celebrates top media innovations. This setup makes Inter BEE a place where the latest trends and future ideas come together. Introducing CloudTV, our custom OTT streaming solution CloudTV is a flexible streaming solution that SupremeTech has created for businesses. Built on strong cloud technology, CloudTV lets businesses create their own streaming platforms quickly and easily. It allows for high-quality video streaming that can be viewed on any device—smartphones, computers, or smart TVs. CloudTV is also secure and easy to customize, so each business can make the platform look and feel their own. CloudTV solves problems around scaling and technical complexity. Whether a business is large or small, CloudTV’s setup makes streaming simple and reliable. By supporting the latest streaming standards, CloudTV ensures great video quality across different screens and devices. This makes CloudTV a smart choice for businesses that want to reach viewers with a smooth and simple streaming experience. Get in Touch with SupremeTech If you’re interested in a streaming solution that is simple, reliable, and flexible, come visit our booth at Inter BEE 2024. We’re ready to discuss how CloudTV can help meet your unique streaming needs. You can also reach out to SupremeTech directly to explore how we can create a custom streaming platform for your business. Let’s work together to make streaming easy and engaging with CloudTV.

            14/11/2024

            116

            Linh Le

            OTT Streaming

            +1

            • Our success stories

            SupremeTech & Enlyt Showcase CloudTV Streaming Solution at Inter BEE 2024

            14/11/2024

            116

            Linh Le

            Our success stories

            +0

              SupremeTech welcomes GITS Group to the first GITS CEO Summit in Da Nang

              SupremeTech is excited to announce that we are co-hosting the GITS CEO Summit 2024 in Da Nang. As a proud member of the GITS Group, we look forward to welcoming leaders from around the world to this annual gathering. The summit is our largest internal event, where top executives will discuss technology trends, opportunities, and challenges for the upcoming year. We will focus on innovation, global strategies, and building a stronger GITS community. Why Da Nang? The summit will take place in Da Nang, which is not only known for its beautiful beaches and modern facilities but also for the thriving hub of technology in Vietnam. This vibrant city provides an ideal setting for leaders to connect, explore new business ideas, and share valuable insights. Da Nang is also home to many tech companies and startups advancing Vietnam’s position on the global technology map. By hosting the GITS CEO Summit here, SupremeTech aims to highlight Da Nang’s strategic importance and underscore its potential to be an international center for digital innovation. The Significance of the GITS CEO Summit 2024 The GITS CEO Summit 2024 will take place on December 06, bringing together over 70 CEOs from GITS member companies across Vietnam, Australia, Germany, South Korea, and Singapore. We will exchange ideas on technology trends, opportunities, and challenges for the coming year to drive business growth. We will also review the past year’s activities, share plans for 2025, and honor members who have made outstanding contributions to GITS. This year, the summit will be held at the beautiful Naman Retreat Resort, marking a fresh chapter in their journey toward tech excellence. This summit will be a crucial gathering for industry leaders and tech experts, offering meaningful connections through focused conference sessions, a poolside dinner party under the stars, expert talks on manufacturing and finance, and plenty of networking opportunities for everyone involved. This summit goes beyond the normal conference event. It’s a spontaneous gathering hub that puts technology discussion in a practical context and accelerates union among tech leaders. As collaboration becomes ever more important, this summit will help address tech development challenges and inspire fresh ideas for the future. Key Themes “Global Connections, Technology Adoptions” Under the theme "Global Connections. Technology Adoption," the summit aims to foster meaningful conversations about new technologies and how they affect Vietnam's economy. The agenda includes: 1. Keynote presentation: Vietnam IT Report by Dragon Capital2. Panel discussion: Digital Transformation in Manufacturing3. Panel discussion: ESG Compliance & Opportunities for Growth4. Panel discussion: Vietnam IT Goes Global: Challenges and Lessons Learned At the end of the gathering, our CEO members will engage in a joyful gala dinner to celebrate the past year milestones. The event is expected to inspire technology leaders by both insightful talks and vibrant connections. The GITS Summit 2023 successfully took place in Hanoi Look back on the success of SupremeTech and GITS in Vietnam IT Day 2024 SupremeTech and GITS previously teamed up to host Vietnam IT Day 2024, an event that left a strong impression on Vietnam’s IT community and beyond. This event, held in Sydney, Australia, brought together IT leaders to discuss the future of Vietnam’s tech industry. The focus was on strengthening Vietnam’s reputation as a global tech player, and it was highly successful in facilitating meaningful connections between Vietnamese IT companies and international partners. Learn more about Vietnam IT Day 2024 here. Building on the success of Vietnam IT Day, SupremeTech and GITS are excited to expand our vision for the GITS CEO Summit 2024. Want to stay updated about the event, let's follow us for more. See you in Da Nang!

              13/11/2024

              47

              Ngan Phan

              Our success stories

              +0

                SupremeTech welcomes GITS Group to the first GITS CEO Summit in Da Nang

                13/11/2024

                47

                Ngan Phan

                Customize software background

                Want to customize a software for your business?

                Meet with us! Schedule a meeting with us!