I create a TS assertion function, Later, I use it before passing the request DTO to the API service in a UI event handler.
function assertIsGetCampaignPackageReqDTO(
value: any,
): asserts value is GetCampaignPackageRuquestDTO {
if (!value.campaignId || !value.packageCode) {
throw new Error('campaignId or packageCode is empty!');
}
}
const onSearchFormSubmit = async (e: FormEvent<HTMLFormElement>) => {
e.preventDefault();
try {
assertIsGetCampaignPackageReqDTO(searchCondition);
const { value } = await getCampaignPackageQuery.execute(searchCondition);
if (value?.code === '0') {
setCampaignPackages(campaignPackages.concat(value.result));
}
} catch (error) {
message.error(error.message);
}
};
Should I use try...catch statement with the assertion function and show the error message to users? Or, I should validate the legality(if statement) of the request DTO before using the assertion function. The assertion function is only used for passing the TSC check?
Or this:
function assertIsGetCampaignPackageReqDTO(
value: any,
): asserts value is GetCampaignPackageRuquestDTO {
if (!value.campaignId || !value.packageCode) {
throw new Error('value is not GetCampaignPackageRuquestDTO');
}
}
const onSearchFormSubmit = async (e: FormEvent<HTMLFormElement>) => {
e.preventDefault();
if (!searchCondition.campaignId || !searchCondition.packageCode) {
return message.error('campaignId or packageCode is empty!');
}
assertIsGetCampaignPackageReqDTO(searchCondition);
const { value } = await getCampaignPackageQuery.execute(searchCondition);
if (value?.code === '0') {
setCampaignPackages(campaignPackages.concat(value.result));
}
};