cast()
cast<
T>(obj):T
Casts a value to a target type for test access to private members.
๐ Why is this a Hidden Gem?
Encapsulates unsafe casts (as unknown as T or as any, ...) in one place. No more // eslint-disable-next-line @typescript-eslint/no-explicit-any scattered across test files.
Type Parametersโ
T: T = anyโ
The target type to cast to.
Parametersโ
obj: unknownโ
The value to cast.
Returns: Tโ
The value cast to the target type.
Sinceโ
2.0.0
Exampleโ
class MyClass {
private secret = 42;
}
const instance = new MyClass();
const exposed = cast<{ secret: number }>(instance);
expect(exposed.secret).toBe(42);
Use Casesโ
Access private members ๐โ
Bypass TypeScript visibility modifiers to test internal state. Essential for white-box testing of classes.
class Counter {
private count = 0;
}
const instance = new Counter();
const internals = cast<{ count: number }>(instance);
expect(internals.count).toBe(0);
Force incompatible typesโ
Pass intentionally wrong types to test error handling paths.
// Test that function handles invalid input gracefully
const result = myFunction(cast<string>(123));
expect(result.error).toBe('Expected string');