Say I have two types, BasicUser
and AdminUser
that are unioned into one type User
.
interface UserBase {
name: string
authenticationType: AuthenticationType;
}
interface BasicUser extends UserBase {
authenticationType: 'basicUser';
privileges: string;
}
interface AdminUser extends UserBase {
authenticationType: 'adminUser';
}
export type User = BasicUser | AdminUser;
I am trying to build a schema that can validate both a User
type whether that was constructed as an AdminUser
or BasicUser
.
import * as yup from 'yup';
import { AuthenticationType, User } from './types';
const bobAdmin: User = {
name: 'Bob',
authenticationType: 'adminUser',
}
const sallyBasicUser: User = {
name: 'Sally',
authenticationType: 'basicUser',
privileges: 'read'
}
// Schema validation fails typecheck
const userSchema: yup.ObjectSchema<User> = yup.object({
name: yup.string().required(),
authenticationType: yup.string().oneOf<AuthenticationType>(['basicUser', 'adminUser']).defined().required(),
privileges: yup.string().when('authenticationType', ([authenticationType], schema) => {
if(authenticationType === 'basicUser') {
return schema.required();
}
return schema;
})
});
The validation actually works, but TypeScript is complaining that the schema doesn’t satisfy the User
type.
I’ve tried breaking the schemas into two distinct schemas and using mixed().oneOf([])
, but that didn’t work either.
Are there any workarounds or tips anyone could provide? Thank you.