[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);
};
});
});
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2021-01-04 [Java] Modules
2019-01-04 [Tips + Javascript] Make a unique array
2019-01-04 [Algorithm] Median Maintenance algorithm implementation using TypeScript / JavaScript
2019-01-04 [Tools] Support VS Code Navigation and Autocomplete Based on Webpack Aliases with jsconfig.json
2019-01-04 [Tools] Create a Simple CLI Tool in Node.js with CAC
2016-01-04 [Javascript] JSON.parse API
2016-01-04 [React Testing] Setting up dependencies && Running tests