[Typescript] Force to valid the type by using Valid branded type
Let's we have a form to submit new password. Before we send request to server, we want to force developer to valid the password before sending the request. We can achieve that by using Branded type
declare const brand: unique symbol;
export type Brand<T, TBrand> = T & { [brand]: TBrand };
export type Valid<T> = Brand<T, "Valid">;
So for createUserOnApi
function only accpet Valid<PasswordValues>
, which force developer to call validatePassword
in advance.
interface PasswordValues {
password: string;
confirmPassword: string;
}
const validatePassword = (values: PasswordValues): Valid<PasswordValues> => {
if (values.password !== values.confirmPassword) {
throw new Error("Passwords do not match");
}
return values as Valid<PasswordValues>;
};
const createUserOnApi = (values: Valid<PasswordValues>) => {
// Imagine this function creates the user on the API
};
it("Should fail if you do not validate the values before calling createUserOnApi", () => {
const onSubmitHandler = (values: PasswordValues) => {
// @ts-expect-error
createUserOnApi(values);
};
});
it("Should succeed if you DO validate the values before calling createUserOnApi", () => {
const onSubmitHandler = (values: PasswordValues) => {
const validatedValues = validatePassword(values);
createUserOnApi(validatedValues);
};
});
--- Similar example ---
import { describe, it } from "vitest";
import { Brand } from "../helpers/Brand";
interface User {
id: string;
name: string;
maxConversionAmount: number;
}
type ConvertedCurrency = Brand<number, "ConvertedCurrency">;
type AuthorizedUser = Brand<User, "CurrencyAuthorizedUser">;
// Mocks a function that uses an API to convert
// One currency to another
const getConversionRateFromApi = async (
amount: number,
from: string,
to: string,
) => {
return Promise.resolve((amount * 0.82) as ConvertedCurrency);
};
// Mocks a function which actually performs the conversion
const performConversion = async (
user: AuthorizedUser,
to: string,
amount: ConvertedCurrency,
) => {};
const ensureUserCanConvert = (
user: User,
amount: ConvertedCurrency,
): AuthorizedUser => {
if (user.maxConversionAmount < amount) {
throw new Error("User cannot convert currency");
}
return user as AuthorizedUser;
};
describe("Possible implementations", () => {
it("Should error if you do not authorize the user first", () => {
const handleConversionRequest = async (
user: User,
from: string,
to: string,
amount: number,
) => {
const convertedAmount = await getConversionRateFromApi(amount, from, to);
// @ts-expect-error
await performConversion(user, to, convertedAmount);
};
});
it("Should error if you do not convert the amount first", () => {
const handleConversionRequest = async (
user: User,
from: string,
to: string,
amount: number,
) => {
// @ts-expect-error
const authorizedUser = ensureUserCanConvert(user, amount);
// @ts-expect-error
await performConversion(authorizedUser, to, amount);
};
});
it("Should pass type checking if you authorize the user AND convert the amount", () => {
const handleConversionRequest = async (
user: User,
from: string,
to: string,
amount: number,
) => {
const convertedAmount = await getConversionRateFromApi(amount, from, to);
const authorizedUser = ensureUserCanConvert(user, convertedAmount);
await performConversion(authorizedUser, to, convertedAmount);
};
});
});