All Articles

An `unknown` can't always fix an `any`

Matt Pocock
Matt PocockMatt is a well-regarded TypeScript expert known for his ability to demystify complex TypeScript concepts.

Any any in a codebase is a cause for concern. That's because it disables type checking on the thing it's assigned to.

If you pass an any to a function parameter, you then can't guarantee anything about that function parameter:

const groupBy = (arr: any[], key: any) => {
  const result: any = {};
  arr.forEach((item) => {
    // How do we know that item is an object?
    // Or that it has a property the same
    // as the key we pass in?
    const resultKey = item[key];

    if (result[resultKey]) {
      result[resultKey].push(item);
    } else {
      result[resultKey] = [item];
    }
  });

  return result;
};

An any can also 'leak' across your application.

If we use this function, we're going to get back any and disable type checking in even more places.

Can you spot the 2 errors below?

const array = [
  { name: "John", age: 20 },
  { name: "Jane", age: 20 },
  { name: "Jack", age: 30 },
];

const result = groupBy(array);
// result is any!

result[20].foreach((item) => {
  // item is any!
  console.log(item.name, item.age);
});

So why would an any be added to a codebase in the first place?

One reason could be that you're trying to solve a bug you don't understand.

TypeScript has plenty of hard edges that can feel unintuitive for beginners.

const keys = ["a", "b"];

const obj = {};

for (const key of keys) {
  // Element implicitly has an 'any' type because
  // expression of type 'string' can't be used to
  // index type '{}'.
  obj[key] = key;
}

const keys = ["a", "b"];

// Phew, no more error
const obj: any = {};

for (const key of keys) {
  obj[key] = key;
}

By the way, the best way to solve and error like the above is either with a Record, or with an as type - depending on how specific a type you want obj to be:

const keys = ["a", "b"];

// obj will be typed as a record where its
// properties can be any string
const obj: Record<string, string> = {};

for (const key of keys) {
  obj[key] = key;
}

const keys = ["a", "b"] as const;

// obj will now be typed with the keys 'a' and 'b'
const obj = {} as Record<
  typeof keys[number],
  string
>;

for (const key of keys) {
  obj[key] = key;
}

Another way anys creep into your code is when you don't use enough generics.

Imagine, for a moment, that TypeScript didn't have generics. How would you actually type this function?

// How on earth do you type this function?

const groupBy = (arr, key) => {
  const result = {};
  arr.forEach((item) => {
    const resultKey = item[key];
    if (result[resultKey]) {
      result[resultKey].push(item);
    } else {
      result[resultKey] = [item];
    }
  });
  return result;
};

Let's try our hardest to avoid using any.

We know that the members of the array must be objects, so let's start with a Record<string, unknown>[] type:

const groupBy = (
  arr: Record<string, unknown>[],
  key: string
) => {
  const result = {};
  arr.forEach((item) => {
    const resultKey = item[key];
    if (result[resultKey]) {
      result[resultKey].push(item);
    } else {
      result[resultKey] = [item];
    }
  });
  return result;
};

But we immediately run into issues, because we've said that the values of each item is unknown, and you can't use unknown to index into result:

const groupBy = (
  arr: Record<string, unknown>[],
  key: string
) => {
  const result = {};
  arr.forEach((item) => {
    const resultKey = item[key];

    // Type 'unknown' cannot be used as an index type.
    if (result[resultKey]) {
      //       ^^^^^^^^^

      result[resultKey].push(item);
    } else {
      result[resultKey] = [item];
    }
  });
  return result;
};

So, we try and cast item[key] to string, but this results in even more issues:

const groupBy = (
  arr: Record<string, unknown>[],
  key: string
) => {
  const result = {};
  arr.forEach((item) => {
    const resultKey = item[key] as string;

    // No index signature with a parameter of
    // type 'string' was found on type '{}'.
    if (result[resultKey]) {
      //^^^^^^^^^^^^^^^^^

      result[resultKey].push(item);
    } else {
      result[resultKey] = [item];
    }
  });
  return result;
};

The way to fix this is to add a type annotation to result, to represent the type that we're getting back:

const groupBy = (
  arr: Record<string, unknown>[],
  key: string
) => {
  const result: Record<string, unknown[]> = {};
  arr.forEach((item) => {
    const resultKey = item[key] as string;
    if (result[resultKey]) {
      result[resultKey].push(item);
    } else {
      result[resultKey] = [item];
    }
  });
  return result;
};

No more errors, but the result of groupBy is now always Record<string, unknown[]>:

const array = [
  { name: "John", age: 20 },
  { name: "Jane", age: 20 },
  { name: "Jack", age: 30 },
];

// result is Record<string, unknown[]>
const result = groupBy(array, "age");

Is this preferable to using any?

In one sense, HELL YES.

This gives us proper type-safety on the values of the result, meaning you will catch errors like misspelled array methods:

const result = groupBy(array, "age");

// Property 'foreach' does not exist on type
// 'unknown[]'. Did you mean 'forEach'?
result[20].foreach((item) => {});

But in another sense, we've just changed the problem.

Now instead of having anys spreading across our app, we have unknowns.

The unknown type is extremely "yelly". It errors whenever you access a property or assign it to something that isn't unknown:

const result = groupBy(array, "age");

result[20].forEach((item) => {
  // 'item' is of type 'unknown'.
  item.name;

  // Type 'unknown' is not assignable to type
  // '{ name: string; age: number; }'.
  const typedItem: { name: string; age: number } =
    item;
});

You could go further with validation if you wanted to, but since we already know for sure that item has a name and an age it becomes pointless runtime bloat:

result[20].forEach((item) => {
  if (
    typeof item === "object" &&
    item &&
    "age" in item &&
    "name" in item &&
    typeof item.age === "number" &&
    typeof item.name === "string"
  ) {
    // Hooray, it's a string!
    item.name;

    // Hooray, it's a number!
    item.age;
  }
});

So to recap:

Unnecessary anys in your codebase are bad because they cause bugs.

Unnecessary unknowns in your codebase are bad because they bloat your runtime code with boilerplate.

And from the steps we've seen above, typing a utility function to return the unknowns in the right place is NOT easy.

The way out of this Catch-22 is generics.

The code below is extremely complex, but it perfectly describes the behaviour of the function.

Consumers of the function don't need to worry about anys or unknowns. It behaves exactly as they expect to:

const groupBy = <
  TObj extends Record<string, unknown>,
  TKey extends keyof TObj
>(
  arr: TObj[],
  key: TKey
) => {
  const result = {} as Record<
    TObj[TKey] & PropertyKey,
    TObj[]
  >;
  arr.forEach((item) => {
    const resultKey = item[key] as TObj[TKey] &
      PropertyKey;
    if (result[resultKey]) {
      result[resultKey].push(item);
    } else {
      result[resultKey] = [item];
    }
  });
  return result;
};

const result = groupBy(array, "age");

result[20].forEach((item) => {
  // No errors, no validation needed!
  console.log(item.name, item.age);
});

The big takeaway here is that if you're concerned about anys in your codebase, you need to know generics.

Total TypeScript Core Volume has an entire workshop module dedicated to generics that will give you the knowledge and understanding to avoid implementing suboptimal code that brings uncertainty into your app.

Matt's signature

Share this article with your friends

`any` Considered Harmful, Except For These Cases

Discover when it's appropriate to use TypeScript's any type despite its risks. Learn about legitimate cases where any is necessary.

Matt Pocock
Matt Pocock

No, TypeScript Types Don't Exist At Runtime

Learn why TypeScript's types don't exist at runtime. Discover how TypeScript compiles down to JavaScript and how it differs from other strongly-typed languages.

Matt Pocock
Matt Pocock