DEV Community

Saulo Dias
Saulo Dias

Posted on • Updated on

A safer alternative to 'any' in TypeScript

We've all been there. For some reason we are not really sure what type of object to expect from an API endpoint. Maybe the API has not been defined yet, or whatever. So what do we do?

You've probably seen code like this, because someone knew it was going to be a list of things.

getData(): Observable<any[]> {
  // return this.http.get<any[]>(API_URL); // TODO: Integrate with api
  return of([]);
}
Enter fullscreen mode Exit fullscreen mode

But we can do better than that.

You might not know what type of object to expect, but you probably have a vague idea. Maybe it is going to be a list of objects with keys (strings) which you don't know yet.

In that case you want to do something like this:

getData(): Observable<Record<string, unknown>[]> {
  // return this.http.get<Record<string, unknown>[]>(API_URL); // TODO: Integrate with api
  return of([]);
}
Enter fullscreen mode Exit fullscreen mode

The Record<Keys, Type> type

Constructs an object type whose property keys are Keys and whose property values are Type.
For example, the object:

type SkinfoldSite = 'biceps' | 'triceps' | 'subscapular' | 'suprailiac';

type SkinfoldThickness = Record<SkinfoldSite, number>;

const skinfoldThickness: SkinfoldThickness = {
  biceps: 4.41,
  triceps: 8.63,
  subscapular: 13.29,
  suprailiac: 10.14,
};
Enter fullscreen mode Exit fullscreen mode

The unknown type

This is similar to the any type, but is safer because it’s not legal to do anything with an unknown value. You have to check its type first.
For example:

let unknownValue: unknown;
unknownValue = 10;
unknownValue = 'height';


if (typeof unknownValue == 'string') {
  const unknownKey = unknownValue.toUpperCase();
  // Do something with unknownKey 
} else if (typeof unknownValue == 'number') {
  // Do something else
}
Enter fullscreen mode Exit fullscreen mode

With unknown if you do not check the type, the linter will show a type error, because you are trying to use a method in an object whose type you don't know for sure, which can cause errors in execution time.

In conclusion, it's always a good idea to type your objects correctly, however when not possible, a better alternative is to always go for safer options.

TypeScript: Documentation - Record

TypeScript: Documentation - unknown

Top comments (0)