Shipping with confidence · Lesson 11 of 12 · 10 min
Testing your types
Your types are code. When a refactor changes them, you want a failing test, not a silent widening to any.
import { expectTypeOf, test } from "vitest";
import { first, pluck } from "./utils";
test("first infers the element type", () => {
expectTypeOf(first([1, 2])).toEqualTypeOf<number | undefined>();
});
test("pluck rejects unknown keys", () => {
// @ts-expect-error: "emial" is not a key of User
pluck(users, "emial");
});Run them with vitest --typecheck. They never execute; they only type-check.
@ts-expect-error is a test on its own: if the line stops erroring, TypeScript reports the comment as unused.
Exercise: add a type test for the Result type from the error-handling lesson.