Trick or Type Guard? Surviving `unknown` with is-kit ๐ŸŽƒ

Trick or Type Guard? Surviving `unknown` with is-kit ๐ŸŽƒ

โ—1 โ—18 โ—59
calendar_today โ€ข schedule5 min read
โ€” Originally published at dev.to

Hoi hoi! ๐Ÿ‘‹

I'm @nyaomaru, a frontend engineer who is scared of horror things ๐Ÿ™€

Happy Halloween! ๐ŸŽƒ๐Ÿ‘ป

Tonight, we're exploring a haunted TypeScript project.

There are zombies ๐ŸงŸ, ghosts ๐Ÿ‘ป, mysterious pumpkins ๐ŸŽƒ, and a terrifying vampire ๐Ÿง› waiting for us.

And they all have something to do with TypeScript types!

Our mission?

Survive the night without losing type safety! ๐Ÿ˜ธ

Let's go!

halloween is-kit


๐ŸงŸ Chapter 1: The Unknown Living Dead

It's a dark and spooky night.

Suddenly, something crawls out of the grave! ๐ŸงŸ

const creature: unknown = JSON.parse('{"message":"BRAAAINS!"}');

Oh! An unknown creature!

Let's see what it wants.

console.log(creature.message);
// โŒ 'creature' is of type 'unknown'.

WHAT?! ๐Ÿ™€

TypeScript won't let us!

But why?

Well, because we don't actually know what creature is.

It might be a zombie.
It might be a ghost.
It might even be a cute little cat. ๐Ÿ˜ธ

unknown means we haven't verified the value yet.

Unlike any, TypeScript won't let us access arbitrary properties on an unknown value.

And that's actually a good thing!

Let's try something simpler.

import { isString } from "is-kit";

const voice: unknown = JSON.parse('"BRAAAINS!"');

if (isString(voice)) {
  console.log(voice.toUpperCase());
  // BRAAAINS!
}

YAY! ๐ŸŽ‰

We survived our first encounter!

Of course, we could also use typeof voice === 'string' here.

For a single check, that's perfectly fine!

But what happens when our monsters become bigger and more complicated?


๐ŸŽƒ Chapter 2: The Big Pumpkin of Unknown

Look!

A GIGANTIC PUMPKIN! ๐ŸŽƒ

And apparently, it's full of candy.

But nobody knows what's really inside.

const pumpkin: unknown = JSON.parse(`{
  "name": "Big Pumpkin",
  "candies": ["Chocolate", "Lollipop", "Cookie"],
  "spookyLevel": 99,
  "keeper": {
    "name": "cat",
    "friendly": true
  },
  "secret": "Meow!"
}`);

That's a pretty big object.

Can we just grab the candy?

console.log(pumpkin.candies);
// โŒ 'pumpkin' is of type 'unknown'.

Not again! ๐Ÿ˜ฟ

We need to check what's inside before touching anything.

Fortunately, we have struct!

import {
  arrayOf,
  isBoolean,
  isNumber,
  isString,
  optionalKey,
  struct,
} from "is-kit";

const isPumpkin = struct({
  name: isString,
  candies: arrayOf(isString),
  spookyLevel: isNumber,
  keeper: struct({
    name: isString,
    friendly: isBoolean,
  }),
  secret: optionalKey(isString),
});

We composed several small guards into one big pumpkin guard.

  • isString checks strings.
  • isNumber checks finite numbers.
  • arrayOf(isString) checks an array of strings.
  • struct checks nested object shapes.
  • optionalKey allows a property to be missing.

Now, let's open the pumpkin!

import { safeParse } from "is-kit";

const result = safeParse(isPumpkin, pumpkin);

if (result.valid) {
  console.log(result.value.candies);
  // ['Chocolate', 'Lollipop', 'Cookie']

  console.log(result.value.keeper.name);
  // cat ๐Ÿ˜ธ
}

We found the candy!!! ๐Ÿฌ๐ŸŽ‰

When validation succeeds, result.value has the type inferred from our guards.

And when validation fails?

const cursedPumpkin = {
  name: "Cursed Pumpkin",
  candies: "100 candies",
  spookyLevel: 99,
  keeper: {
    name: "cat",
    friendly: true,
  },
};

const result = safeParse(isPumpkin, cursedPumpkin);

console.log(result);
// { valid: false }

The candies were a string, not an array!

Our guard rejected the cursed pumpkin.

And here's the important part.

safeParse doesn't magically fix or convert invalid values.

It simply tells us whether the value passed our guard.

Also, struct allows extra properties by default. If you need to reject additional own enumerable string keys, you can use { exact: true }.

Nice and simple!


๐Ÿฌ Chapter 3: Trick or Type Guard!

Ding dong! ๐Ÿ””

TRICK OR TREAT!!! ๐Ÿ˜ธ

Someone hands us a mysterious gift.

function receiveGift(): unknown {
  return Math.random() > 0.5 ? "Chocolate" : { spiders: 100 };
}

const gift: unknown = receiveGift();

Wait.

Is it candy?
Or is it a box full of spiders?! ๐Ÿ•ท๏ธ๐Ÿ˜ฑ

We need a way to check!

And this time, we want to accept either a string or a number.

Let's combine our guards with or!

import { isNumber, isString, or } from "is-kit";

const isTreat = or(isString, isNumber);

function trickOrTreat(gift: unknown) {
  if (isTreat(gift)) {
    // gift: string | number
    return `๐Ÿฌ Treat: ${gift}`;
  }

  return "๐Ÿ‘ป Trick!";
}

Now let's try it!

trickOrTreat("Chocolate");
// ๐Ÿฌ Treat: Chocolate

trickOrTreat(100);
// ๐Ÿฌ Treat: 100

trickOrTreat({ spiders: 100 });
// ๐Ÿ‘ป Trick!

YAY!!! ๐Ÿฌ

No spiders for us today!

This is one of my favorite things about is-kit.

We don't need to write one giant validator.

We can build small guards, combine them, and reuse them wherever we need.

Small guards. Simple composition. Useful TypeScript narrowing.

That's the idea!

But wait,
Something is coming.
Something TERRIFYING.


๐Ÿง› Final Boss: The Vampire Called any

Suddenly, the lights go out.

The door opens.

A mysterious figure appears in the darkness.

It's... COUNT ANY!!! ๐Ÿง›๐Ÿ’€

The most terrifying vampire in our TypeScript project! And he has a very dangerous power.

He can make TypeScript stop checking our operations!

const visitor: unknown = JSON.parse('{"name":666}');

A mysterious visitor has arrived.

Normally, TypeScript protects us from accessing properties before we verify them.

But Count Any has a trick.

THE CURSE OF as any! ๐Ÿง›

const vampire = visitor as any;

// The vampire ignores type safety!
console.log(vampire.name.toUpperCase());

No TypeScript error!

Wait, What?! ๐Ÿ™€

Does that mean the code is safe?

At runtime

TypeError: vampire.name.toUpperCase is not a function

๐Ÿ’€ GAME OVER ๐Ÿ’€

Count Any didn't turn the number into a string.

He just convinced TypeScript to stop checking it!

That's what makes any dangerous.

It allows operations without requiring proof that they'll work.

But unknown behaves differently.

const visitor: unknown = JSON.parse('{"name":666}');

console.log(visitor.name.toUpperCase());
// โŒ TypeScript stops us!

TypeScript refuses to continue until we check the value.

So how do we defeat Count Any?

With a Type Guard, of course! ๐Ÿ˜ธ

import { isString, struct } from "is-kit";

const isFriendlyGuest = struct({
  name: isString,
});

if (isFriendlyGuest(visitor)) {
  console.log(visitor.name.toUpperCase());
} else {
  console.log("๐Ÿง„ Not tonight, Count Any!");
}

And just like that

THE VAMPIRE HAS BEEN DEFEATED! ๐Ÿง„๐ŸŽ‰

Well, at least this particular cursed value has been rejected.

A Type Guard checks the actual runtime value, while a type assertion only changes what TypeScript believes about it.

One important detail, neither unknown nor any changes the value at runtime.

They are TypeScript types.

The difference is what the compiler allows us to do before verifying the value.

And that's why unknown is usually the safer choice for untrusted data.


๐Ÿ˜ธ Epilogue: We Survived Halloween!

What a night!

We met the Unknown Living Dead, opened a gigantic pumpkin, collected some candy, and defeated Count Any!

So, what did we learn?

Monster TypeScript lesson
๐ŸงŸ Unknown Living Dead unknown prevents unchecked operations
๐ŸŽƒ Big Pumpkin struct validates object shapes
๐Ÿฌ Trick or Treat or combines reusable type guards
๐Ÿง› Count Any any bypasses normal type checking

Of course, any isn't always evil.

Sometimes it's useful when dealing with legacy code or difficult integrations.

But when working with API responses, parsed JSON, and other untrusted values, keeping them as unknown until validation is usually a much safer approach.

And is-kit makes those checks easy to compose and reuse!

If you want to explore more, check out the official guide ๐Ÿ‘‡

๐Ÿ“– How to Validate unknown in TypeScript Without a Schema Library

And remember

The real monster isn't unknown. It's unchecked any. ๐Ÿง›

Happy Halloween!!! ๐ŸŽƒ๐Ÿ‘ป

If you enjoyed this little TypeScript adventure, check out is-kit!

{% embed https://github.com/nyaomaru/is-kit %}

And if you like the project, a โญ would make this little cat very happy! ๐Ÿ˜ธ

Thank you for reading! ๐Ÿคฒ

Want more #opensource & #typescript deep dives?

Join 6,072+ developers sharing real benchmarks, code breakdowns, and projects. Free forever.

2 Comments

1 vote
1

More Posts

TypeScript Complexity Has Finally Reached the Point of Total Absurdity

Karol Modelski - Apr 23

How I Built a React Portfolio in 7 Days That Landed โ‚น1.2L in Freelance Work

Dharanidharan - Feb 9

AAIF Hits 10 Projects. Its CTO on What to Adopt Now and the Security Gaps Left Open

Tom Smithverified - Oct 23

The Sovereign Vault โ€” A Comprehensive Guide to Protocol-Driven AI

Ken W. Algerverified - Jun 4

Tuesday Coding Tip 02 - Template with type-specific API

Jakub Neruda - Mar 10
chevron_left
1k Points โ€ข 78 Badges
Heerlen, the Netherlands โ€ข nyaomaru-portfolio.vercel.app
23Posts
22Comments
42Connections
Funny Frontend Engineer! ? Living in the Netherlands.

Related Jobs

View all jobs โ†’

Commenters (This Week)

1 comment
1 comment

Contribute meaningful comments to climb the leaderboard and earn badges!