Property-Based Testing Implementation in TypeScript
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Property-Based Testing runs in O(n) time and O(n) space, in TypeScript as in every other language.
- ✓Same runtime library as JavaScript -- `fast-check` -- but it ships its own declarations, so `fc.Arbitrary<T>` is a real generic and `fc.record({ a: fc.integer() })` infers `Arbitrary<{ a: number }>` with no cast.
- ✓Reviewers insist on an explicit `const a: fc.Arbitrary<User> = ...` annotation so inference drift shows up at compile time, and on generating through the same smart constructor production uses (`parse(): T | null`, then `.filter((x): x is T => ...)`) rather than an `as T` cast.
- ✓The TypeScript trap: Types are erased, so an `as` cast inside `.map()` makes the arbitrary a lie: a branded `UserId` produced by `fc.string().map(s => s as UserId)` has the brand at compile time and arbitrary garbage at runtime, and the property then proves a theorem about inputs your code will never receive -- while missing the ones it will.
- ✓Runtime cost is identical to JavaScript -- the types vanish. What you pay instead is compilation: a `ts-node` run (default, non-`--transpile-only`) typechecks the whole test tree before a single example is generated, and deeply generic arbitraries (nested `fc.record` inside `fc.letrec`) are exactly the shapes that blow up tsc inference time, so a 3-second property can sit behind a 10-second typecheck.
What Property-Based Testing actually is
Property-Based Testing in TypeScript: what you actually reach for
TypeScript implementation
import fc from 'fast-check';
type UserId = string & { readonly __brand: 'UserId' };
interface User {
readonly id: UserId;
readonly age: number;
readonly nickname?: string;
}
// Parse, do not cast: the smart constructor is what the property really tests.
const parseUserId = (s: string): UserId | null =>
/^[a-f0-9]{8}$/.test(s) ? (s as UserId) : null;
const userId: fc.Arbitrary<UserId> = fc
.hexaString({ minLength: 8, maxLength: 8 })
.map(parseUserId)
.filter((x): x is UserId => x !== null);
const user: fc.Arbitrary<User> = fc.record(
{ id: userId, age: fc.integer({ min: 0, max: 130 }), nickname: fc.string() },
{ requiredKeys: ['id', 'age'] },
);
fc.assert(
fc.property(fc.array(user), (users: readonly User[]): boolean => {
const byId = new Map<UserId, User>(users.map((u) => [u.id, u] as const));
return byId.size <= users.length;
}),
);
Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe TypeScript-specific trap
Performance in TypeScript, beyond the O(n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which TypeScript type or library should I use for Property-Based Testing?
Same runtime library as JavaScript -- `fast-check` -- but it ships its own declarations, so `fc.Arbitrary<T>` is a real generic and `fc.record({ a: fc.integer() })` infers `Arbitrary<{ a: number }>` with no cast. `fc.record(shape, { requiredKeys: [...] })` types the remaining keys optional, `fc.letrec` types mutually recursive arbitraries, and `fc.constantFrom(...)` narrows to a literal union. There is no type reflection in TS, so nothing derives an arbitrary from an interface: bridges go through a runtime schema, e.g. the third-party `zod-fast-check`, or you write the generator by hand.
What is the most common TypeScript mistake when implementing Property-Based Testing?
Types are erased, so an `as` cast inside `.map()` makes the arbitrary a lie: a branded `UserId` produced by `fc.string().map(s => s as UserId)` has the brand at compile time and arbitrary garbage at runtime, and the property then proves a theorem about inputs your code will never receive -- while missing the ones it will. The optional-property trap is the same shape: `fc.record` with `requiredKeys` omits the key entirely, whereas `T | undefined` yields a key present and set to `undefined`. `deepStrictEqual` and `Object.keys` distinguish those two; `tsc` (without `exactOptionalPropertyTypes`) does not.
How does Property-Based Testing actually perform in TypeScript?
Runtime cost is identical to JavaScript -- the types vanish. What you pay instead is compilation: a `ts-node` run (default, non-`--transpile-only`) typechecks the whole test tree before a single example is generated, and deeply generic arbitraries (nested `fc.record` inside `fc.letrec`) are exactly the shapes that blow up tsc inference time, so a 3-second property can sit behind a 10-second typecheck. Precompile the test tree or run under a transpile-only loader (`tsx`, `swc`, `esbuild`) in the inner loop and keep `tsc --noEmit` as a separate CI step. Time complexity is O(n) and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialBefore paying full price for a tool, check the student deals on AI and developer tools listed on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.