In this article, we review snippt/guards. You will learn the following:
What is sniptt/guards?
Guards usage in Twenty codebase.
What is sniptt/guards?
Sniptt/guards is a comprehensive collection of type guards for JavaScript and TypeScript; Inspired by Elixir. Has zero dependencies.
Foreword on JavaScript data types and data structures
The latest ECMAScript standard defines nine types:
- Six Data Types that are primitives, checked by
typeofoperator:
undefined: typeof instance === "undefined"
Boolean: typeof instance === "boolean"
Number: typeof instance === "number"
String: typeof instance === "string"
BigInt: typeof instance === "bigint"
Symbol: typeof instance === "symbol"
Structural Types:
Object:typeof instance === "object". Special non-data but structural type for any constructed object instance also used as data structures: newObject, newArray, newMap, newSet, newWeakMap, newWeakSet, newDateand almost everything made withnewkeyword;Functionnon data structure, though it also answers fortypeofoperator:typeof instance === "function". This answer is done as a special shorthand forFunctions, though everyFunctionconstructor is derived fromObjectconstructor.Structural Root Primitive
null:typeof instance === "object". Special primitive type having additional usage for it's value: if object is not inherited, thennullis shown;
Source: Guards Readme
Below is a simple example usage from the docs:
import { primitives } from '@sniptt/guards';
primitives.isNumber(val);
Guards usage in Twenty codebase.
I found the below code in Twenty codebase.
import { isNull, isUndefined } from '@sniptt/guards';
export const isDefined = <T>(
value: T | null | undefined,
): value is NonNullable<T> => !isUndefined(value) && !isNull(value);
isUndefined is defined as shown below in the Guards docs.
import { isUndefined } from '@sniptt/guards';
let val: undefined | null;
if (isUndefined(val)) {
// TypeScript will infer val: undefined
} else {
// TypeScript will infer val: null
}
and this isDefined is used in usePlan hook as shown below:
import { isDefined } from 'twenty-shared/utils';
export const usePlans = () => {
const { data, loading, error } = useListPlansQuery();
const isPlansLoaded = isDefined(data?.listPlans);
About me:
Hey, my name is Ramu Narasinga. Email: ramu.narasinga@gmail.com
Tired of AI-generated code that works but nobody understands?
I spent 3+ years studying OSS codebases and wrote 350+ articles on what makes them production-grade. I built an open source tool that reviews your PR against your existing codebase patterns.
Your codebase. Your patterns. Enforced.

Top comments (0)