I encountered the same issue when trying to convert schemas using patternProperties
into TypeScript interfaces with the hope that the openapi-typescript library would handle it, but it seems the support is not available at the moment. (Refer to the issue I raised).
The challenge with patternProperties
essentially revolves around whether we can constrain a string in TypeScript to only accept values that match a particular regex pattern. You can find an explanation here. To summarize, regular expression constraints are not directly supported (although there is an ongoing proposal for this feature), indicating that converting schemas utilizing patternProperties
to corresponding TypeScript interfaces is currently unachievable generically. For simpler patterns, a similar concept called template literal types exists.
In your specific scenario, however, your primary concern is not really about patternProperties
. In fact, given the provided schema:
"styles": {
"title": "Style Definitions",
"description": "Style definition",
"type": "object",
"patternProperties": {
"^.*$": {
...
}
}
}
The suggested interface actually serves as an effective translation:
interface Styles {
[key: string]: ...,
}
Thus, despite the title of your query, the actual conundrum pertains to integrating oneOf
functionality from JSON schema into a TypeScript interface. There is no direct equivalent in TS, and the solution varies based on the definitions of Definition1
and Definition2
. Refer to this question.
Addendum:
The misuse of oneOf
by openapi-typescript library through a TS union (relevant code) has been noted. As showcased, the following TypeScript snippet is valid:
interface First {
aString: string;
aNumber?: number;
}
interface Second {
aString: string | boolean;
}
const tester: First | Second = {
aString: 'asdgasdf'
}
console.log(tester);
However, since tester
satisfies both First
and Second
, if this were to be the JSON schema "equivalent" using oneOf
, then tester
would fail validation.