abi
abi2y ago

Simple type narrowing/type guard/assertion (?)

Is there really no simpler way of doing this without any and without external deps?
export function isFooBarBaz(
value: unknown,
): value is { Foo: { Bar: { Baz: string } } } {
return typeof value === "object" &&
value !== null &&
"Foo" in value &&
typeof value.Foo === "object" &&
value.Foo !== null &&
"Bar" in value.Foo &&
typeof value.Foo.Bar === "object" &&
value.Foo.Bar !== null &&
"Baz" in value.Foo.Bar &&
typeof value.Foo.Bar.Baz === "string";
}
export function isFooBarBaz(
value: unknown,
): value is { Foo: { Bar: { Baz: string } } } {
return typeof value === "object" &&
value !== null &&
"Foo" in value &&
typeof value.Foo === "object" &&
value.Foo !== null &&
"Bar" in value.Foo &&
typeof value.Foo.Bar === "object" &&
value.Foo.Bar !== null &&
"Baz" in value.Foo.Bar &&
typeof value.Foo.Bar.Baz === "string";
}
(What's the exact name for what I'm doing here btw? I confuse the terms.)
3 Replies
marvinh.
marvinh.2y ago
If you want to simplify that a little bit you can drop the "KEY" in my.obj.prop checks there since the typeof expression after that takes care of that. I've seen folks using libraries like zod or @badrap/valita for building up schemas which can be used to do validate an unknown value if it matches a type.
abi
abi2y ago
yeah, i'm actually resorting to zod now, even though i feel like i shouldn't need to :/ but i do have pretty deep and complex objects