The oneOf Keyword
In support of the OpenAPI Specification oneOf
schemas, Speakeasy SDKs provide language-specific implementations based on idiomatic unions (when available) or using generated supporting objects that allow type safety by using an enum
discriminator.
Supporting Objects
Assuming your spec has a Pet
component, consider this oneOf
block:
oneOf: - type: string - type: integer - $ref: "/components/schemas/Pet"
How Speakeasy generates supporting objects for your SDK depends on the language of the SDK.
Speakeasy leverages native TypeScript support for unions to represent oneOf
schemas. A union type is generated to represent the different possible types defined in the oneOf
schema.
Requests
Assume you have an operation that allows the user to fetch a pet by submitting the pet's name, ID, or complete pet object:
/pet: get: operationId: fetchPet parameters: - name: pet schema: oneOf: - type: string - type: integer - $ref: "/components/schemas/Pet"
const sdk = new SDK();sdk.pets.fetchPet("Fido"); // stringsdk.pets.fetchPet(123); // numbersdk.pets.fetchPet({ id: "p-123" }); // Pet object
Responses
Sometimes you may have a response that specifies a oneOf
schema. For languages that do not natively support unions, Speakeasy will create supporting objects to deserialize the oneOf
response into the correct object type. No supported objects are needed for languages with native union types, so Speakeasy will deserialize into the native type.
For example, this schema:
/pet_id: get: operationId: petId responses: "200": description: OK content: application/json: schema: title: res oneOf: - type: string - type: integer
Will result in these response types:
type PetIdRes = string | number;