From fb04abaeae6a56db088d57fc03af36c61bdbd161 Mon Sep 17 00:00:00 2001 From: Hugo ChunHo Lin Date: Sat, 24 Aug 2024 13:48:07 +0800 Subject: [PATCH] feat(type-guards): add type guards for About, LifeStyle, TechStack, and SocialMedia --- src/lib/type-guards.ts | 53 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 src/lib/type-guards.ts diff --git a/src/lib/type-guards.ts b/src/lib/type-guards.ts new file mode 100644 index 00000000..0587dc62 --- /dev/null +++ b/src/lib/type-guards.ts @@ -0,0 +1,53 @@ +import { LifeStyle, TechStack, SocialMedia, About } from "./constants"; + +export const isLifeStyle = (obj: unknown): obj is LifeStyle => { + if (!isObject(obj)) return false; + return ( + typeof obj.icon === 'string' && + typeof obj.title === 'string' && + typeof obj.text === 'string' + ); +}; + +export const isTechStack = (obj: unknown): obj is TechStack => { + if (!isObject(obj)) return false; + return ( + typeof obj.id === 'string' && + typeof obj.src === 'string' && + typeof obj.alt === 'string' + ); +}; + +export const isSocialMedia = (obj: unknown): obj is SocialMedia => { + if (!isObject(obj)) return false; + return ( + typeof obj.githubUsername === 'string' && + typeof obj.mediumUsername === 'string' && + typeof obj.twitterUsername === 'string' && + typeof obj.linkedinUsername === 'string' + ); +}; + +export const isAbout = (obj: unknown): obj is About => { + if (!isObject(obj)) return false; + return ( + isSocialMedia(obj.socialMedia) && + typeof obj.header === 'string' && + typeof obj.subHeader === 'string' && + typeof obj.pronouns === 'string' && + Array.isArray(obj.introductions) && + obj.introductions.every(item => typeof item === 'string') && + Array.isArray(obj.lifestyle) && + obj.lifestyle.every(item => isLifeStyle(item)) && + Array.isArray(obj.programmingLanguage) && + obj.programmingLanguage.every(item => isTechStack(item)) && + Array.isArray(obj.devOps) && + obj.devOps.every(item => isTechStack(item)) + ); +}; + + +export const isObject = (object: unknown): object is Record => { + return typeof object === 'object' && object !== null && !Array.isArray(object); +}; +