Header image

TypeScript – How To Avoid “Any”?

26/09/2022

2.11k

  • 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

    1.71k

    Software Development

    +0

      TypeScript And “Any” Type

      07/09/2022

      1.71k

      When Technology Meets a Pioneering Spirit

      Our culture

      +0

        When Technology Meets a Pioneering Spirit

        SupremeTech’s Hackathon 2025 is not just a coding competition, it’s a place where bold ideas are tested, limits are broken, and new connections are formed. Every team carries its own story – about why they joined, their role in the group, or what they expect to gain after this intense yet inspiring journey. Among them, we had the chance to chat with Quang Dũng, a Technical Leader at SupremeTech, who is participating in a Hackathon for the very first time – while also taking on the role of team leader. Usually busy with deadlines and lines of code, this Hackathon is his opportunity to step away from routine work and challenge himself in a completely different way. We listened to his thoughts on challenges, pioneering spirit, and what he hopes to take away from this event. Let’s join SupremeTech and Quang Dũng in this conversation about the Hackathon! Q&A with Quang Dũng 1. Is this your first time joining a Hackathon?Yes, this is my first Hackathon. Everything feels new: the intensity, the pressure, and how teamwork changes under strict time limits. I wanted to experience this firsthand and compare it with the usual way of running projects. 2. What made you decide to sign up for the event?I wanted to challenge myself – to see how far I can go applying AI in real-world work. This is an opportunity for me and my team to pioneer ways of leveraging AI Copilot in a small group project of 3–5 people, while learning new workflows and testing practical applications. And of course, the prizes are also very attractive – hard to resist! Who knows, maybe I can go home and tell my wife that just two days of Hackathon brought back 50 million VND! (laughs). 3. What is your role in the team? If given the choice, what field would you like your project to be applied to?I’m the team leader – responsible for planning, setting the initial direction, and building a sample demo so everyone has a clear vision. In other words, I set the rhythm so the whole team can work smoothly together. If I had the chance to choose a project topic, I’d want it applied to practical areas like booking/reservation systems or internal management tools such as resource and project management. These fields are highly relevant to business needs and can create immediate value. 4. If you had to describe SupremeTech’s AI Hackathon in three words, what would they be? Challenge – Pioneer – Connection. Challenge: because everyone here must push beyond their own limits.Pioneer: because we are applying the latest AI technologies to real-world problems.Connection: connecting people, ideas, and the future of technology. 5. What do you expect to gain from this Hackathon? In my daily work, I’m often involved in project estimation. I expect this event will help me learn how to integrate AI Copilot into product development workflows. That could make estimations more accurate, save time, and improve overall efficiency at the company. In other words, what I look forward to most is not just the prize, but the knowledge and experience that can truly be applied to work. >> Read related articles: How a Hackathon Changed My Life – A Personal Story from the CEO of SupremeTech Closing SupremeTech’s Hackathon is more than a tech playground, it’s an opportunity for each individual to test themselves, learn, and break past their own limits. Stay tuned for the next tech journeys at SupremeTech, where even the smallest ideas can spark big changes!

        22/08/2025

        135

        Our culture

        +0

          When Technology Meets a Pioneering Spirit

          22/08/2025

          135

          tips when joining AI Hackathon

          Knowledge

          +0

            How Could You Join a Hackathon Without Knowing This?

            In the ever-evolving world of programming, the emergence of intelligent support tools is changing the way we write code. Copilot, often described as “AI-powered Pair Programming”, promises to revolutionize the workflow of software developers. In this article, I’ll focus on GitHub Copilot, the AI tool I personally use every day when coding. What is GitHub Copilot? GitHub Copilot is an AI assistant integrated into IDEs (VS Code, IntelliJ IDEA/PyCharm, Neovim) developed by GitHub and OpenAI. It provides context-aware code suggestions as you type, and includes Copilot Chat for Q&A directly inside the IDE. Key Advantages of GitHub Copilot Faster coding: Reduce time spent on repetitive tasks with context-aware suggestions (functions, code blocks, basic tests).Learn new technologies quickly: Get API/syntax examples directly in your IDE; ask further via Copilot Chat.Automate boring work: Scaffold endpoints, write boilerplate, create sample tests, suggest snippets, and ensure consistent formatting.Seamless IDE integration: Works in VS Code, JetBrains, Neovim; suggestions appear as ghost text/inline as you type. Limitations to Keep in Mind Not always accurate: May generate syntax, logic, or performance errors.Solution: Always review, run lint/tests, and benchmark when needed.Security & copyright risks: Could resemble public code or leak if sensitive data is pasted.Solution: Enable “block suggestions matching public code,” avoid entering secrets, follow organizational policies.Risk of dependency: Over-reliance may weaken fundamental coding skills.Solution: Use Copilot for speed, but keep code reviews and tests.Limited domain knowledge: Suggestions may not fit specific business contexts.Solution: Break down requests, add examples/constraints, manually refine critical parts. Quick Start (VS Code) Install extensions: GitHub Copilot and (optional) GitHub Copilot Chat.Log in to GitHub and enable suggestions in Settings.Create a new file, describe requirements in Vietnamese/English within comments or docstrings.Press Tab to accept, Esc to skip. Check IDE shortcuts for more. Simple Examples Just comment your request, and GitHub Copilot will write code for you. Example 1: Utility function to validate email (JavaScript) // Write function isValidEmail(email: string): boolean function isValidEmail(email) { return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email); } Note: The regex above is basic — adjust according to project needs. Example 2: Quick API skeleton (Node.js/Express) // Create route GET /health that returns { status: 'ok' } app.get('/health', (req, res) => { res.json({ status: 'ok' }); }); Example 3: Basic unit test (Jest) // Write test for sum(a,b): 1+2=3, -1+1=0 test('sum basics', () => { expect(sum(1, 2)).toBe(3); expect(sum(-1, 1)).toBe(0); }); Tips for Using GitHub Copilot Effectively Write clear descriptions/comments: specify input, output, constraints, and examples.Always check & optimize code: run lint/tests, review performance, security.Break down complex requests: guide step by step for more accurate suggestions.Use Copilot Chat to research/explain, but always verify with original docs. Key Notes Enable “block suggestions matching public code” in organizational projects.Avoid pasting secrets (keys, credentials, sensitive data) into prompts. Conclusion GitHub Copilot is an AI assistant that helps you code faster, learn new tech quickly, and automate repetitive tasks — but you still need to review, test, and follow security policies. My Personal Experience Coding with GitHub Copilot Before using GitHub Copilot: Spent lots of time on repetitive, structured code.Slowed down by switching between coding and researching online. When first trying Copilot: Felt efficiency in simple features/functions.Struggled with complex features — Copilot often generated unnecessary code.Spent extra time reviewing Copilot’s output. After long-term use: Significantly reduced time on repetitive tasks (boilerplate, data mapping, simple CRUD, …).More consistent code (naming, structure), better documentation (docs, README) thanks to quick suggestions.Changed workflow: “comment-first” or “test-first” to guide Copilot, using Chat to refine and explain.Formed a risky habit: accepting Copilot’s suggestions too quickly without reviewing. Start Small & Measure Effectiveness Enable Copilot in your IDE, try with a utility function or basic test, turn on the “block public code” filter, and avoid pasting secrets. After one week, measure effectiveness (task completion time, amount of boilerplate written manually, number of minor bugs), then decide how much to apply in projects. Good luck using GitHub Copilot effectively — and may you achieve great success at the Hackathon!

            22/08/2025

            121

            Anh Nguyen T.

            Knowledge

            +0

              How Could You Join a Hackathon Without Knowing This?

              22/08/2025

              121

              Anh Nguyen T.

              CEO of SupremeTech Hackathon

              Our culture

              +0

                How a Hackathon Changed My Life – A Personal Story from the CEO of SupremeTech

                Written by Binh Nguyen, CEO of SupremeTech, from his own Hackathon journey Hi everyone,Today I’d like to share an experience that truly shaped who I am, not just as a professional, but as a builder. This is the story of how a Hackathon transformed my mindset from being just a developer into becoming a tech builder. Before moving into business analysis and later management, I started out as a Front-end Developer. Back in 2016, I was self-learning HTML, CSS, and React.js. Then in 2017, I had the chance to join a Hackathon that completely changed how I approached product development. It was the turning point that made me realize the difference between being a coder and being a builder. Step 1: Accepting the Challenge The Hackathon was organized by the Da Nang Business Incubator in collaboration with the Embassy of Israel, with support from venture capitalists and incubators from Israel. At that time, the prizes weren’t particularly big. But as someone new to the industry, eager to start a career and even dream of building a startup, I felt I had to join. Honestly, another reason was my competitive nature, I wanted to prove that even though I came from a non-tech background and had only been coding for a year, I could still stand shoulder-to-shoulder with others. Step 2: Preparing, Planning and Strategy For those unfamiliar, a Hackathon is a short, intensive coding competition where individuals or teams create a product in just a few days. You start from an idea, build it, and then present it on the last day - the demo day. The products are evaluated by the judges based on the Hackathon’s criteria. Our theme that year was straightforward: turn a startup idea into a product in just two days. If coding is a sport, then Hackathon is like a championship match. To build an app in such a short time, we had to prepare carefully, especially the methods to build a complete app as fast as possible. Boilerplates, bootstrap, pre-made components, even self-made code generation tools to save time… techniques that now are nothing difficult, but the goal of a Hackathon is always the same: build fast and ship immediately! With everything ready, we headed off to the competition. Step 3: Code, Bug, Hack and Chaos After the opening ceremony, we chose our topic and immediately got to work. Our topic was an app to find venues and make group reservations. Like most projects, the first 50% of the codebase went smoothly. We managed to build it within half a day. But the problems started when we moved into the core features and tricky logic like date pickers, slot reservations, venue data, etc. Ideas kept coming, we kept coding, and bugs showed up just as much. By 9 p.m., we were exhausted, buried in bugs, with no clear way forward, and nothing ready for the demo the next morning. So we decided to stop coding and discuss how to deliver on time. After more than an hour of debate, here’s how we planned the remaining work: Stop implementing backend logic and data crawlers, use front-end mockups to ensure demo flowDeploy on Heroku to save time on server setup and have a live productSpend extra time preparing slides to explain during the demo In the end, the chaos turned into something more organized. The funny part was that I, the front-end guy, had to keep coding, while our back-end guy ended up making the slides. Step 4: Demo – The G Hour After polishing things up until the last minute, we got on stage to demo. This part was quite similar to a sprint review, except that we had to stand on stage and present to a big audience. For everyone at ST now, sprint reviews are done very well already, so nothing more to add here. What surprised us was that the judges, especially the Israeli experts, didn’t pay much attention to the detailed features we had spent so much effort on. Instead, they asked “general” questions like: What is the technology that makes this product better than others?In what situations would users actually want to use this product? Step 5: Reflection – What I Gained We didn’t win for two main reasons: The software was quite complete but didn’t clearly show competitive advantages.Vietnamese users at that time didn’t really have the habit of booking tables/services via apps. Although we lost and felt quite upset at that moment, looking back now, I gained so much more: Confidence in setting up the initial codebase and preparing projects for productionUnderstanding that the value of technology lies in efficiency and competitiveness, not the number of featuresRealizing that users don’t care how much effort we put into building an app, they just want their problem solved in the best wayDelivering code fast and continuously, without waitingPreparation and choosing the right topic are the two keys to winningWith the right mindset, I could work with the best developers without losing confidence, even with less knowledge and experience Lastly: Try It Once—It Might Change You Too Hackathon changed me from being just a self-taught coder into a true tech builder. The mindset I gained in those two days has helped me a lot throughout my career until now. I believe many others will also learn valuable lessons from upcoming quality Hackathons. 100 million VND in prizes are waiting for you at the SupremeTech Hackathon this September 2025. Enjoy!

                21/08/2025

                143

                Binh Nguyen T.

                Our culture

                +0

                  How a Hackathon Changed My Life – A Personal Story from the CEO of SupremeTech

                  21/08/2025

                  143

                  Binh Nguyen T.

                  Customize software background

                  Want to customize a software for your business?

                  Meet with us! Schedule a meeting with us!