Skip to content

fix(types): improve Root shorthand method return types#3105

Open
mahmoodhamdi wants to merge 1 commit intohapijs:masterfrom
mahmoodhamdi:fix/root-shorthand-return-types
Open

fix(types): improve Root shorthand method return types#3105
mahmoodhamdi wants to merge 1 commit intohapijs:masterfrom
mahmoodhamdi:fix/root-shorthand-return-types

Conversation

@mahmoodhamdi
Copy link
Copy Markdown
Contributor

The Root-level shorthand methods (Joi.allow(), Joi.valid(), Joi.required(), etc.) currently declare Schema as their return type. Since these methods delegate to this.any()[method]() at runtime (source), they always return an AnySchema. Using the broader Schema union type loses this specificity and breaks method chaining in TypeScript — e.g. Joi.allow('x').required() doesn't resolve to AnySchema.

Changes

  • Updated return types for all Root shorthand methods (allow, valid, equal, invalid, disallow, not, required, exist, optional, forbidden, preferences, prefs, custom) from Schema to AnySchema
  • Added missing only() and strip() declarations to the Root interface — these are registered at runtime but were absent from the type definitions
  • Added type tests verifying method chaining works correctly with the new return types

Before

const s = Joi.allow('x');  // Schema (union type — no .required() etc.)
const s2 = Joi.required(); // Schema

After

const s = Joi.allow('x');            // AnySchema — supports chaining
const s2 = Joi.allow('x').required(); // AnySchema ✓
const s3 = Joi.only().valid('a');     // AnySchema ✓
const s4 = Joi.strip();              // AnySchema ✓

All tests pass: npm test (1796 tests, 100% coverage, types, lint).

…g declarations

Change Root-level shorthand methods (allow, valid, invalid, required,
optional, forbidden, etc.) to return AnySchema instead of Schema, since
they delegate to this.any().method(). This enables proper method chaining
with full type inference.

Also add missing only() and strip() declarations to the Root interface,
which are registered at runtime but were absent from the type definitions.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant