iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
📘

Introducing type-predicates-generator: Automatically generate type guards from TypeScript definitions

に公開
2024/04/06
6件

I have created a tool that automatically generates user-defined type guards (type predicates) and assertion functions from TypeScript type definitions, and I'd like to introduce it! By automatically generating user-defined type guards, which can be prone to incorrect implementations, you can easily and safely protect your application's types!

https://github.com/d-kimuson/type-predicates-generator

Type Predicates and Their Issues

When typing values coming from the outside, such as via API calls or JSON parsing, or when using libraries without type definitions, if you use type annotations or as as is, you won't be able to notice if an unexpected value arrives.

type Task = {
  id: number
  titile: string
  description: string
}

const task: Task = JSON.parse("...") // Write annotation for a function that returns the any type
task /* :task */ // In reality, even values other than any will be treated as the Task type

If types differ from the actual data, the benefits provided by TypeScript decrease in terms of both application safety and developer experience, which is not desirable.

In such cases, using type predicates (v is <Type>) allows you to perform type guarding with a user-defined function and type values safely.

type_predicate_sample
function isTask(value: unknown): value is Task {
  return (
    typeof value === 'object' &&
    value !== null &&
    'id' in value &&
    typeof value.id === 'number' &&
    'title' in value &&
    typeof value.title === 'string' &&
    'description' in value &&
    typeof value.description === 'string'
  )
}

if (isTask(task)) {
  // If isTask returns true, treat task as the Task type
  task /* :Task */
}

While this is safer than using as or type annotations, TypeScript does not verify whether the implementation of this type predicate function is actually correct at all.

As an extreme example, even a nonsensical implementation like const isTask = (v: unknown): v is Task => true will narrow the type to Task without any warnings.

Of course, you probably wouldn't write such an implementation, but:

  • Cases where the implementation was correct when written, but the Task type was later changed (e.g., adding properties), making isTask inappropriate.
  • Cases of simple implementation errors (as you can see from isTask, writing property checks for objects properly is quite complex, and there are also union types and child element checks for arrays, so there is plenty of room for mistakes).

Due to these factors, inappropriate runtime check functions can be introduced.

Also, since writing a type predicate for every single type is tedious, it is common to psychologically compromise by using type annotations or as without writing the type predicate itself.

Introducing type-predicates-generator

type-predicates-generator solves these problems by automatically generating type predicate functions from type definitions.

It can be installed via npm.

https://www.npmjs.com/package/type-predicates-generator

$ yarn add -D type-predicates-generator  # or npm

By passing the appropriate options to the type-predicates-generator command, the type predicate functions are automatically generated.

$ yarn run type-predicates-generator -f 'path/to/types/**/*.ts' -o './type-predicates.ts'

It automatically generates predicate functions from exported type declarations (type aliases and interfaces) within files matching path/to/types/**/*.ts and writes them to type-predicates.ts.

As a trial, running type-predicates-generator on the Task type used in the example above results in the following automatic generation:

Automatically generated predicate definition
import type { Task } from "path/to/your-type-declare"

const isNumber = (value: unknown): value is number => typeof value === "number"
const isString = (value: unknown): value is string => typeof value === "string"
const isObject = (value: unknown): value is Record<string, unknown> =>
  typeof value === "object" && value !== null && !Array.isArray(value)

export const isTask = (arg_0: unknown): arg_0 is Task =>
  isObject(arg_0) &&
  "id" in arg_0 &&
  isNumber(arg_0["id"]) &&
  "title" in arg_0 &&
  isString(arg_0["title"]) &&
  "description" in arg_0 &&
  isString(arg_0["description"])

All that's left is to use the automatically generated functions to protect your application when values arrive from the outside.

 import { isTask } from 'path/to/type-predicates'

 fetch("path/to/api").then(async (data) => {
-  const json: Task = await data.json(); // Dangerous typing without checking if it's actually the Task type
+  const json /* :any */ = await data.json();
+  if (!isTask(json)) throw new Error('Oops');  // Throw an exception if the check fails

   json /* :Task */
 })

Now you can safely and easily type values coming from the outside.

By specifying the -a option, you can additionally automatically generate assertion functions. In the case above, using an assertion function would be more appropriate.

// Additionally automatically generated with -a
function assertIsTask(value: unkonwn): asserts value is Task {
  if (isTask(task))
    throw new TypeError(`value must be Task but received ${value}`)
}

// Usage
const json /* :any */ = await data.json()
assertIsTask(json) // An exception occurs if it fails
json /* :Task */

Since it's automatically generated, there's no effort required to write predicates, which lowers the psychological hurdle, and it also solves the problem of it being difficult to keep up with changes to Task.

It also supports watch mode (-w), so you can start the watcher during development to reflect changes immediately.

Please refer to the repository for other options.

https://github.com/d-kimuson/type-predicates-generator#cli-options

What can and cannot be checked

Basically, I built it to support all data structures that can be received via JSON (so if anything is missing, I would appreciate it if you could open an issue).

https://github.com/d-kimuson/type-predicates-generator/issues

On the other hand:

  • Functions/Methods
  • Promise
  • Data structures with circular references (e.g., obj1.recursive = obj2, obj2.recursive = obj1)
      • Because properties would check each other during property checks, resulting in an infinite loop.

The above items cannot be checked.

Regarding type operations, basically all are supported.

Even if complex types such as Mapped Types or Conditional Types are used, if they ultimately resolve to a JSON-serializable type, or its intersection or union types, they can be generated without any problems.

Generated from complex types
// Source: Partial uses Mapped Types
type PartialTask = Partial<Task>;

// Generated function: Generated from the finally resolved type
export const isPartialTask = (arg_0: unknown): arg_0 is PartialTask =>
  isObject(arg_0) &&
  ((arg_1: unknown): boolean => isUnion([isUndefined, isNumber])(arg_1))(
    arg_0["id"]
  ) &&
  ((arg_1: unknown): boolean => isUnion([isUndefined, isString])(arg_1))(
    arg_0["title"]
  ) &&
  ((arg_1: unknown): boolean => isUnion([isUndefined, isString])(arg_1))(
    arg_0["description"]
  )

Using with openapi-generator

In frontend development, it's common to use tools like openapi-generator or aspida to automatically generate response types.

While it's possible to include these directly in the generation target for type-predicates-generator, the type definitions tend to be vast and can take time to generate, so you can also re-export only the ones you use.

  • That said, even when I tried it with a 4000-line type definition generated by GraphQL Code Generator for my personal blog, it only took a little over 5 seconds, so it might not be a major concern.

For this use case, I've included not only type declarations but also re-exported type definitions in the generation target.

export { Category } from "../typescript-axios/api"

There is a concrete example in the example directory of the repository. You can see that functions are generated in type-predicate.ts from the type definitions re-exported via re-export.ts.

How is it Implemented?

It uses the Compiler API to extract type information from files specified via glob and automatically generate the code.

While I will leave the details of the Compiler API to other articles, the flow is as follows:

  1. Search for Nodes within the target files to pick up type alias and interface declaration nodes.
  2. Recursively extract types from the declaration nodes using the TypeChecker and convert them into easily outputtable type information defined uniquely.
  3. Generate the code based on the extracted type information.

https://github.com/d-kimuson/type-predicates-generator/blob/main/src/compiler-api/compiler-api-handler.ts

https://github.com/d-kimuson/type-predicates-generator/blob/main/src/generate/generate-type-predicates.ts

Other Solutions

A major library that solves the problem of type predicate implementations potentially deviating from type definitions is io-ts.

Usage example
import { isRight } from "fp-ts/lib/Either";
import * as t from 'io-ts'

const TaskIO = t.type({
  id: t.number,
  title: t.string,
  description: t.string,
})

export type Task = t.TypeOf<typeof TaskIO>

// Usage example
const data /* :any */ = JSON.parse('...')
const result = TaskIO.decode(data)
if (isRight(result)) {
  const task /* :Task */ = result.right
}

io-ts uses its own syntax to define types for runtime checking, and you receive the TypeScript types from that (t.TypeOf(typeof Task)).

It is a very good library, but since you cannot write type definitions using standard TypeScript types:

  • It cannot handle cases where you want to define API types from existing TS types via type operations.
  • It cannot handle cases where type definitions are automatically generated by tools like openapi-generator (as you would need to define types for runtime checks in io-ts separately from the type definitions).

In such situations, type-predicates-generator becomes a good option.

Conclusion

So, that was an introduction to type-predicates-generator!
Already just after its creation, it's a tool that makes it easy to enhance type safety, so I'd be happy if you'd give it a try!
I'm also looking forward to your PRs and Issues!

Discussion

acomaguacomagu

typescript-is との違いが知りたい

1
きむそんきむそん

typescript-is では ttypescript 依存の transformer の機能を使用してビルドファイルの中にランタイムチェック関数を生成しますが、type-predicates-generator はトランスパイル前のコードとしてランタイムチェック関数を書き出します。型を変える度にコード生成をする(あるいは watch しておく)デメリットはありますが、挙動は暗黙的になりにくいです

あとは、バンドルサイズには結構差が出るはずです。typescript-is は is<型> の箇所に毎回すべてのランタイムチェック関数(プリミティブ型のチェックからその他諸々)を生成するはずなので。type-predicates-generator は対象ファイルから一括で単一のファイルにランタイムチェック関数を作成するという仕様上、チェック関数の共通化がしやすいです。プリミティブ型や Union 型等のチェック関数はすべて共通のものを使用していますし、例えば Task[] の型チェックには定義済みの isTask 関数を使用します。結果、使用量が多いほどバンドルサイズの差は大きくなると思います

kawarimidollkawarimidoll

参考になるツール・記事をありがとうございます。

最初の方に出ている「type_predicateのサンプル」のコードで、typeof value.title === 'number' typeof value.description === 'number'となっている箇所がありますが、ここは'string'との比較が正しいのではないでしょうか。

1
きむそんきむそん

ここは'string'との比較が正しいのではないでしょうか。

ほんとですね、'string' が正しいです。ご指摘ありがとうございます。修正しておきます