Typescript typeguard strategy: fancy way to check unknown types
Tags: typescript, webdev, api, coding
Published: 2024-01-19 01:05:20

## Introduction
Typescript is an incredible combination with javascript, by the way just javascript is becomes unfeasible because it does not have primitive variable types. But, to life is not just sweet, and the 'unknown' and 'any' values exists to frighten us.

## How it works
However, not everything in the life of a TypeScript developer is wonderful. You've probably already made a request to a rest API that has a super big response. Then you needed to validate all this complex data. This is tedious and error-prone...

Well, a good developer is to write things that work well and easy to maintain.

But somethimes we don't need to add a new package to the project.

That's why I bring it in an easy way. Which can help you validate types like a piece of cake.

The idea of ​​this strategy is simple: to facilitate and reduce code smells simply with small functions that check the types of values.

In the end of the day, the use is simple and the result is magical.

We define functions that check a value for a type. In other words, a function for each given type: boolean, string, number, object etc. 

See the code below.

```typescript
// this base functions is a callback called in the nested objects and arrays
export type TypeGuard<T> = (val: unknown) => T

// custom convenient typeguard thats make a way to customize the values
export type CustomTypeGuard<T> = (
  callback?: (val: T) => T
) => TypeGuard<T>

export const string: CustomTypeGuard<string> = 
  (callback) => (val: unknown) => {
    if (typeof val !== 'string') 
      throw new Error("Invalid string value")
    return  callback ? callback(val) : val
}

export const number: CustomTypeGuard<number> = 
  (callback) => (val: unknown) => {
    if (typeof val !== 'number')
      throw new Error("Invalid number value")
    return callback ? callback(val) : val
}

export const boolean: CustomTypeGuard<boolean> = 
  (callback) => (val: unknown) => {
    if (typeof val !== 'boolean') 
      throw new Error("Invalid boolean value")
    return callback ? callback(val) : val
}

export function array<T>(inner: TypeGuard<T>) {
    return (val: unknown): T[] => {
        if (!Array.isArray(val)) 
          throw new Error("Invalid array value");
        return val.map(inner)
    }
}

export function object<
  T extends Record<string, TypeGuard<any>>
>(inner: T) {
  return (val: unknown): { 
    [P in keyof T]: ReturnType<T[P]> 
  } => {
      if (val === null || typeof val !== 'object') 
        throw new Error("Invalid object");

      const out: { [P in keyof T]: ReturnType<T[P]> } = {} as any;

      for (const k in inner) {
          out[k] = inner[k]((val as any)[k])
      }

      return out
  }
}
```
Take a look to the callback function defined in the `CustomTypeGuard`. The ideia behind this, is to add a function to handle each value in the final 'schema' object. This is great for manipulate e process some data from a api response for example.

With these functions defined we can use them like code below.

```typescript
import { string, object, array, number, boolean } from "typeguard"

// the schema receive a function
// this function validates an object using the schema as base
const schema = array(
    object({
        name: string((val) => `${val} doe`),
        id: number((val) => val + 1),
        birthdate: string(
          (val) => new Date(val).toLocaleDateString("pt-br")
        ),
        ready: boolean(),
        parents: array(
            object({
                name: string(),
            })
        ),
    }),
)

// Wich this line below we can get the type of the previous created schema and use this before
type User = ReturnType<typeof schema>

const noTypedUser = [{ 
  name: 'jhon', 
  id: 1, 
  birthdate: new Date().toISOString(), 
  ready: true,
  parents: [{ name: 'jhon' }] 
}]

// if any value is not ok
// an error is thrown
const user: User = schema(noTypedUser);

console.log(user);
```

Can you see this code running in the ts playground [here](https://www.typescriptlang.org/play?ts=5.3.3&ssl=60&ssc=19&pln=41&pc=1#code/FAFwngDgpgBAKpKBxArgQwE4BMA8cB8MAvDABQBuaANgFwwoB2A1gwPYDuDAlMYXKIhgBhFAGcQrALYJoqTLgLEyAY2pUARmmVMA-HQrU6cHkT4m+iOdjz5gwZawbiY4jAEsGAczojxUmcjo1q4enoQkpKpUGlpM5mSUtPTMbJzxAN7AMNkwbgBmZODQrAWJMACERCQA5CFe1TwgABYYHDAMUOwwAKIYrRikAEQAkgyJblguIO5eMIkoUINcWTkYUCAoGAzZUTHaMDowu5raBlQ8dInAAL52Dk4g7SiS6lAYPmIS0pZBuAzPrww4RUahOcV4CUMyRYHG4EMyOVyBVIRSgJTm1AqVRg1X+LzeDRgzVaXQ6XV6-SGo3GkzxgIxVAWSxW2TWGy2R1BsQOnOiYLOFwZNzujmc6lYrCoUDQDA+fm+sl+OHFkulDGBkS52niZzojBhaXhLKRhUQ6LKlRqKqlMsJxLaZJ6fVYAxGY2oExg1rVDKZy0RbM222O3MOIdOiUFV1uwDyjGUIDcjhgmAwaDANlIHg673gP3kNh4CNW6yDkKS+tS3CMAG0ALpGxGI-JkcoAQT66YAdG5RB202ABY0Wg7Ok7KW6aSnO2BfYsuABuY0B0scxJdyRoCBZhg5-05W4xmBxhgJpPbVjqABWUATeBgUAAHiAoAwsKIYAAlW8u3B1TwADR5oqBYymA+AQTuOZGEWxqBhyurQlWXB0OkMA1gACrk2xMFAYDonAdZ0N+7IMAEeCYXWhDXI2TbZC2ZzENi-zRDAAA+bFEmapSYpaOKXjeCZ2iOpJjhSLpUu6VCegJt4gEsS7Ljk9zOKwKAgKh6FYR4MC4fhBSEcRq5kYgFEYVRMA0SQ6Q0WgH5gYpdHZHkLoqKKjxMNh2F7jAxZOTkakgDWTANiQ2ZvMFdakIxdkpgwYBcJF+50UeTnwRe6nGoeIoPC4yhNFAm5KKm6akMaskJqQflNgwaCSFAdD-tFkYQgABgAJOkiQ0VgrBQK1XAAUp9FYHQdJvM11DxGUADUMAAIyDcNXpuBgzRYGgL6NdMoSTecEKOgAIptUACl2EgADKsFEUDHS+ADKO1eEMEAgAAtOoGBLEt-lrGgWBgHQ3oyqQP1ORAmCviAoh0CVg7LYiFUgFVCNObV9XbTMnig0N-mItcyVNmD2QE0NywCNAMAAKqiG8SgkUG5Gouioj5YVaC2PY7ntKwARYDTdMkDWaHow1OJXk0jjVEBEx0PNQHqKt60nWNY53adXDnawwz3QA8o9WM4zAf0A3Q0wLEBENrAw0N0ML7R1WL1QS1LlkNtcdZc7lYhvHQAsYEorMFZupBsHz-uLjloiql2VCsNjPsYIuQA).

Can you get the code snippet in gist [here](https://gist.github.com/levymateus/ec7e76f29939d2d1b20113716918b49e).

Be Happy :smile:

## Conclusion
Today, in the community, there are thousands of extremely good technologies. However, a large package is often not needed to solve a simple problem. All it takes is a simple, well-done implementation and we can achieve what we want quickly. 

The typeguard strategy with typescript allows us to define a 'schema' object that can check the validity of the type of a value as well as make any change/validation of complex data through a simple callback without something large and difficult to understand, leaving the code clean and easy to read.

### References

- [How to correctly use TypeScript types for your API response](https://medium.com/@wujido20/runtime-types-in-typescript-5f74fc9dc6c4)