Header image

TypeScript – How To Avoid “Any”?

26/09/2022

942

  • 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

    660

    Software Development

    +0

      07/09/2022

      660

      TypeScript And “Any” Type

      react native vs kotlin multiplatform

      Software Development

      +0

        React Native vs. Kotlin Multiplatform: Which one is better?

        Hi tech fellows! Continuing the series comparing different development frameworks, this week we will talk about React Native vs. Kotlin Multiplatform. The comparison unveils the similarities and differences between the two popular technologies for iOS and Android app. This article will cover these main criteria: PerformanceCompatibility with Native APIsDevelopment ExperienceSuitability for Different Types of ProjectsTime Efficiency Performance: Native vs. JavaScript React Native uses JavaScript and a bridge to communicate with native components. This makes it a solid choice for many applications, but it can face performance issues with complex UI or heavy animations. The JavaScript bridge adds overhead, which may cause delays in rendering or interactions for more performance-intensive apps. React Native is suitable for apps like social media platforms, where performance is important but not critical. Kotlin Multiplatform, on the other hand, compiles shared code to native code. Since Kotlin Multiplatform uses Kotlin, which is native to Android, and compiles seamlessly to native code for iOS, it has the advantage of being closer to the metal. This results in better performance, especially for apps that need to process data quickly or have complex UIs. Therefore, Kotlin is a good choice for high-performance apps, like games. Compatibility with Native APIs: Bridging the Gap React Native provides an easy way to access native APIs through JavaScript. However, it might not have built-in support for every API you need. In such cases, you will have to rely on third-party libraries or write custom native modules. This extra step can increase development complexity, especially if you're dealing with platform-specific features. React Native can handle most native APIs but may require more effort when using platform-specific features. Kotlin Multiplatform offers direct access to native APIs. You can write native code for both iOS and Android where needed. This makes it highly compatible with native device features without relying heavily on third-party libraries or custom modules. It also reduces the chances of compatibility issues since you're working with native code. If your app relies on complex features like camera controls or Bluetooth functionality, Kotlin Multiplatform allows for seamless integration with these APIs. Development Experience: Simplicity vs. Flexibility React Native offers a smoother and simpler setup process. Developers familiar with JavaScript can start building apps right away, making it a popular choice for web developers transitioning to mobile development. Its hot-reloading feature also allows for faster development cycles by letting you see changes in real-time. As a result, React Native is ideal for teams with a strong JavaScript background and those looking to get a product to market quickly. Kotlin Multiplatform provides more flexibility but requires familiarity with Kotlin. Therefore, Kotlin Multiplatform is better suited for experienced developers who want more control over performance and platform-specific code. The learning curve is steeper for developers who aren't used to native development, but it's rewarding for those who need greater control over their code. The ability to share business logic across platforms while maintaining separate native UI components allows more customization. Suitability for Different Types of Projects React Native is great for projects where speed and simplicity are top priorities. It’s widely used for apps where the user interface is relatively simple and consistent across platforms. React Native also has a large community and a wealth of third-party libraries, making it easier to find resources and support. React Native can be a good choice for e-commerce apps or social media apps, where time-to-market and a consistent experience across platforms are more important than maximum performance. Kotlin Multiplatform excels in projects where performance, security, and deep integration with native systems are crucial. It's particularly well-suited for projects where business logic is shared, but UI elements need to be customized for each platform. Kotlin Multiplatform is ideal for fintech or health apps that require a high degree of security, performance, and native features. Community and Ecosystem Support React Native has been around since 2015 and boasts a large, active community. There are many libraries and tools available to make development faster and easier. However, maintaining these third-party libraries can sometimes become an issue, as some libraries may not be updated as quickly as needed. Kotlin Multiplatform is newer but is backed by JetBrains and Google, making it a strong contender in the long run. Its community is growing, but it may not have as many pre-built libraries or resources as React Native yet. However, since Kotlin is the official language for Android, it's likely that support for Kotlin Multiplatform will continue to grow. Conclusion: Which Should You Choose? Choose React Native if:Your team has strong JavaScript experience.You need to get an app to market quickly.Performance is not the most critical factor.You prefer using pre-built libraries for common features.Choose Kotlin Multiplatform if:You want native performance and access to platform-specific APIs.Your project involves complex features or high-performance requirements.You prefer sharing business logic but building platform-specific UI.You want a future-proof solution backed by strong industry support. Both React Native and Kotlin Multiplatform are excellent tools, but your choice should depend on the specific needs of your project. Each framework brings unique benefits to the table, so it’s essential to align your decision with your development goals. SupremeTech provide high-skilled React developers for your project. Book a free consultation with us now!

        10/10/2024

        49

        Software Development

        +0

          10/10/2024

          49

          React Native vs. Kotlin Multiplatform: Which one is better?

          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

            273

            Our success stories

            +0

              06/09/2024

              273

              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

                405

                Our success stories

                +0

                  12/08/2024

                  405

                  SupremeTech co-organized Vietnam IT Day 2024 in Sydney

                  Customize software background

                  Want to customize a software for your business?

                  Meet with us! Schedule a meeting with us!