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);
};
});
标签:Typescript,Force,Valid,values,const,PasswordValues,type,createUserOnApi From: https://www.cnblogs.com/Answer1215/p/17025109.html