Skip to content

Instantly share code, notes, and snippets.

@CodeByAidan
Created April 29, 2024 15:26
Show Gist options
  • Save CodeByAidan/a5b3ade9991cbf220a68cc89dec2512a to your computer and use it in GitHub Desktop.
Save CodeByAidan/a5b3ade9991cbf220a68cc89dec2512a to your computer and use it in GitHub Desktop.
most typescript thing i've wrote, will update when things get worse
type Category = {
title: string;
items: Array<{ name: string }>;
};
type Config = {
categories: Record<string, Category>;
};
function isCategory(obj: unknown): obj is Category {
return (
typeof obj === 'object' &&
obj !== null &&
'title' in obj &&
'items' in obj &&
Array.isArray((obj as Category).items) &&
(obj as Category).items.every(
(item) => typeof item === 'object' && 'name' in item
)
);
}
function createWebsite<T extends Config>(config: T): void {
Object.entries(config.categories).forEach(([key, category]) => {
if (isCategory(category)) {
console.log(`Category title: ${category.title}`);
category.items.forEach((item, index) => {
console.log(`Item ${index + 1}: ${item.name}`);
});
}
});
}
@CodeByAidan
Copy link
Author

javascript equivalent is something like:

function isCategory(obj) {
  return (
    typeof obj === 'object' &&
    obj !== null &&
    'title' in obj &&
    'items' in obj &&
    Array.isArray(obj.items) &&
    obj.items.every(
      (item) => typeof item === 'object' && 'name' in item
    )
  );
}

function createWebsite(config) {
  Object.entries(config.categories).forEach(([key, category]) => {
    if (isCategory(category)) {
      console.log(`Category title: ${category.title}`);
      category.items.forEach((item, index) => {
        console.log(`Item ${index + 1}: ${item.name}`);
      });
    }
  });
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment