Header image

TypeScript – How To Avoid “Any”?

26/09/2022

791

  • 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

    Table of contents What is TypeScript?Basic typingWhat 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 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 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 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 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 typeSkip/Disable type-checkingTypeScript doesn't complain any or issue any errorDefault 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 TypeScript handbookTypeScript tutorial Author: Anh Nguyen

    07/09/2022

    564

    Software Development

    +0

      07/09/2022

      564

      TypeScript And “Any” Type

      Our success stories

      +0

        SupremeTech and BiPlus co-organized an event for the Da Nang IT community

        Take a look back to exciting moments in the "Work Smarter, Not Harder with Jira" event for Da Nang’s tech community. Organized by BiPlus, Atlassian's strategic partner in Vietnam, in collaboration with SupremeTech, the event focused on leveraging technology to enhance project management and productivity. The event aimed to show how tools like Jira and artificial intelligence (AI) can help make work more accessible and efficient. By using these tools, businesses can save time and get better results. Beginning of a series of activities for the IT community BiPlus and SupremeTech, two prominent names in Vietnam's IT landscape, teamed up to host this event as part of a broader initiative to engage the local tech community.  Mr. Bui Xuan Hien, CEO of BiPlus, started the event with an inspiring welcome speech. His vision for creating a dynamic, fun, and connected space for the Da Nang IT community resonated with the audience. He emphasized that this event is just the beginning of a series of activities to bring together tech enthusiasts to explore smarter, more efficient ways to work. How Jira can be used to optimize workflows The event focused on how Jira, Atlassian’s popular project management tool, can optimize workflows, streamline communication, and boost team collaboration. With the added integration of AI, the future of work is becoming more intelligent, where smart tools reduce manual effort, freeing up time for more strategic tasks. One of the event's key highlights was the presence of Ms. Lexy, Partner Manager for Southeast Asia and Atlassian’s representative for the Asia-Pacific region. She shared valuable insights into Atlassian’s plans for the region, as well as helpful information on how companies can use their tools to work better. Her Q&A session was especially engaging, allowing attendees to ask specific questions about Jira, Atlassian's tools, and how these technologies can support businesses of various sizes. Expert insights on Jira and AI Integration The event featured a diverse lineup of speakers who shared their expertise on a range of highly relevant topics to today’s IT professionals.  Exploring the evolution of offshore development models This session was presented by Mr. Tien Huynh, Project Manager of SupremeTech, to explore how offshore development models have evolved in recent years. With the increasing need for global collaboration and remote work, he highlighted strategies for managing teams across different locations while maintaining high productivity and quality. He also touched on how Jira helps streamline these complex workflows, enabling teams to stay on track no matter where they are. Managing projects effectively with Jira: Best practice from SupremeTech Ms. Hang Duong, another Project Manager from SupremeTech, delved into the practical aspects of using Jira for project management. She shared real-life examples of how her teams have used Jira to break down complex projects into manageable tasks, ensuring clear communication, accountability, and timely delivery. Her presentation was packed with actionable tips for maximizing Jira’s capabilities, from setting up boards and workflows to tracking progress and handling bottlenecks. Using AI to boost project efficiency A particularly exciting session came from Mr. Truong Cong Phuc, Founder of Luviha Group, who discussed how AI transforms project management. From automating routine tasks to providing predictive analytics for decision-making, he demonstrated how AI can significantly reduce the time and effort spent on project management. He also showed how integrating AI with tools like Jira allows teams to focus on high-level strategy and creativity, leaving the mundane work to intelligent algorithms. Lively panel discussion overcomes challenges in IT project management Following these engaging talks, the event transitioned into a lively panel discussion, where all the speakers joined forces to address the audience’s questions. This interactive session allowed participants to voice their challenges, seek advice, and discuss potential solutions with the panel.  The discussion was moderated by Mr. Bui Xuan Hien, CEO of BiPlus, and Mr. Truong Dinh Hoang, Chairman of SupremeTech, who brought their vast experience to the table. The conversation covered various topics, including managing remote teams, overcoming obstacles in project execution, and the future of AI in IT project management. Keynote of “Work Smarter, Not Harder With Jira” event The event wasn’t just about talks and discussions but also a fantastic networking opportunity. Attendees had the chance to connect with like-minded professionals, share experiences, and explore potential collaborations. The atmosphere was lively and positively charged as participants exchanged ideas and insights on improving their work processes and making their teams more efficient. By the end of the "Work Smarter, Not Harder With Jira" event, it was clear that the Da Nang IT community had gained a wealth of knowledge and practical skills they could immediately implement in their personal and professional lives. Whether working on personal projects, leading a team, or managing a company, the insights from this event provided valuable takeaways for everyone involved. Stay tuned for our upcoming events For those who missed out, stay tuned! BiPlus and SupremeTech have more events planned, offering even more opportunities to dive deeper into innovative work management. As the tech landscape continues to evolve, events like these will play a crucial role in keeping professionals at the cutting edge, ready to tackle the challenges of tomorrow with confidence. The Da Nang IT community has just begun its journey toward smarter, more efficient work processes, and with the support of tools like Jira and the integration of AI, the future looks bright! >>> Explore another event: SupremeTech co-organized Vietnam IT Day 2024 in Sydney Contact us if you want to outsource in Vietnam! Let us know if you want to find a local partner who can build great teams that make great products! We have experience working with the world's most demanding nations and are ready to expand our client list.

        06/09/2024

        30

        Our success stories

        +0

          06/09/2024

          30

          SupremeTech and BiPlus co-organized an event for the Da Nang IT community

          vietnam it day

          Our success stories

          +0

            SupremeTech co-organized Vietnam IT Day 2024 in Sydney

            Take a look back Vietnam IT Day 2024 with an overview of Australia-Vietnam's tech outlook and how SupremeTech is helping businesses thrive with our tech solutions! Hi tech fellows, SupremeTech was delighted to be a co-organizer of Vietnam IT Day, a flagship event fostering Australia - Viet Nam tech partnership, hosted by GITS Group. With the participation of more than 180 tech professionals, the event presented Viet Nam as a promising tech solutions partner for Australian, in specific, and global companies, in general. Vietnam IT Day 2024 has successfully unfolded in Sydney last May A third gathering with the support from Australian government and IT community partners After the two successful events in 2019 and 2023, Vietnam IT Day has gained trust and recognition from not only local tech community but Australia's prestigious organisations. Government committee: Australian Trade and Investment Commission (Austrade)Venue sponsor: PwC AustraliaCommunity partners: Business NSW , Haymarket HQ , Australia-Vietnam Leadership Dialogue , Tech Australia Advocates , IT Professionals In Australia , VNITO Alliance Discuss about tech landscape, know-how in Australian market, and more At the event, a lot of interesting tech topics were brought to discussion. Furthermore, the event was fueled up with business chats and networking activities of C-level participants. In the morning sessions, representatives from both side took us on a trip through Australia and Vietnam's dynamic tech ecosystems with a zoom-in focus from manufacturing, automation and human resource standpoints. While morning workshops provide the macro approach to Australia-Vietnam tech relationship, the afternoon talks went deep into how to take advantages from cross-border collaboration and best practices for scouting tech partners. SupremeTech on best practices for IT outsourcing to Viet Nam In an insightful session about offshore development, SupremeTech's CEO - Mr. Binh Nguyen emphasized the importance of market inquiry for newcomers from Australia. The dynamic IT landscape of Viet Nam offers unlimited opportunities, yet contains potential risks if not thoroughly scrutinized. He gave some social and geopolitical background of Viet Nam with funny highlights. He also suggested a few practices that Australian companies should consider when searching for Vietnam-based IT solution providers. Stay tuned for upcoming Vietnam IT Days Together with GITS network, SupremeTech is looking forward to the fruitful collaboration between the tech community of both countries. We're more than excited to be a pioneering part of it. We hope the upcoming Vietnam IT Days attract the participation of not only local IT companies but also Australian big corporations. Regarding our own initiatives in Australia, we are proactively seeking for strategic partners who aim to build long-lasting and, of course, profitable relationship. Our competency in Agile development would certainly be a driving force for any companies seeking for a highly-efficient and cost-optimized engineering team. Call us if you want to outsource to Viet Nam! If you want to find a local partner who knows how to build great teams that make great products, let us know! We worked with the most demanding countries around the world and we cannot wait to add more to the list.

            12/08/2024

            194

            Our success stories

            +0

              12/08/2024

              194

              SupremeTech co-organized Vietnam IT Day 2024 in Sydney

              What is middleware integration

              Online-Merge-Offline Retail

              Software Development

              +0

                What is Middleware Integration for CDI? | Benefits and Examples

                In the last article, we've discussed Customer Data Integration (CDI) and its important role for OMO Retail. This article will continue to dig deeper into a common type of CDI. Middleware integration is a powerful and flexible solution for CDI, particularly suitable for complex, real-time, and scalable integration needs. Check out SupremeTech's success case studies in building a middleware for an online-merge-offline retail corporation in Japan. What is Middleware Integration? Middleware integration in CDI involves using middleware software to connect and facilitate the exchange of data between different systems, applications, and databases. Middleware acts as an intermediary layer. After successfully built, it ensures smooth communication and data flow without requiring direct connections between the integrated systems. It allows different systems to work together seamlessly. Features of Middleware Integration Connectivity: Middleware provides connectors and adapters to link various systems, regardless of their platforms or technologies. By using middleware, retail businesses do not need to waste time syncing the existing systems of different sales platforms. However, they can still make use of the synchronized database across sales channels to serve customers better. Data Transformation: Middleware can transform data formats and structures to ensure compatibility between different systems. Orchestration: Middleware solutions often include workflow and process orchestration capabilities to manage and automate complex data integration tasks. Scalability: Middleware can handle varying volumes of data and scale according to the business’s needs. We have used middleware to bridge the existing offline system and the online store of a retail giant in Japan with millions of customers. Security: Middleware ensures secure data exchange, protecting sensitive customer information during the integration process. Nowadays, data is considered the capital resource of a business. Securing customer data, therefore, is the utmost priority every business owner concerns. Monitoring and Management: Middleware typically offers tools for monitoring data flows, managing integrations, and troubleshooting issues. Examples of Middleware Solutions Apart from a custom middleware, there are several other handy tools when it comes to a bridge software. MuleSoft Anypoint Platform MuleSoft provides a comprehensive integration platform that enables the connection of any application, data, or device with APIs. It supports both on-premises and cloud integrations. Its main features include API management, data transformation, real-time analytics, and pre-built connectors for various systems. Dell Boomi Boomi offers a cloud-based integration platform as a service (iPaaS) that connects applications and automates workflows across hybrid IT environments. Dell Boomi's highlight features are drag-and-drop interface, pre-built connectors, real-time data synchronization, and extensive support for various protocols. Oracle Integration Cloud Oracle Integration Cloud offers a comprehensive solution for integrating applications and data across on-premises and cloud environments. It offers a wide range of features, including but not limited to pre-built adapters, process automation, visual development tools, and robust analytics. Microsoft Azure Logic Apps Azure Logic Apps is a cloud service that automates and orchestrates tasks and workflows by integrating applications, data, and services across organizations. The main functionalities of MS Azure include extensive integration capabilities, built-in connectors, scalability, and flexibility in designing workflows. Benefits of Middleware Integration Middleware integration offers many benefits for businesses. It ensures seamless communication between different systems and enhances operational efficiency. Middleware provides real-time data availability and supports various integration patterns and workflows. Thus, it is adaptable to evolving business needs. Moreover, it transforms data to ensure system compatibility. It also centralizes management, simplifying monitoring and troubleshooting. Additionally, it enhances security by protecting sensitive data during exchanges. Overall, middleware integration improves decision-making and customer experiences. If you need a custom middleware for your unique business, book a free consultation with us! Providing bridging solutions for online-merge-offline retail businesses is one of SupremeTech's best-selling services. Not only do we have abundant experiences but we also implement fast and cost-efficiently. Let us know your current problems and we will tackle them down together!

                15/07/2024

                342

                Online-Merge-Offline Retail

                +1

                • Software Development

                15/07/2024

                342

                What is Middleware Integration for CDI? | Benefits and Examples

                Customize software background

                Want to customize a software for your business?

                Meet with us! Schedule a meeting with us!