Skip to content

Instantly share code, notes, and snippets.

View bennycode's full-sized avatar
🏡
Working from home

Benny Neugebauer bennycode

🏡
Working from home
View GitHub Profile
@bennycode
bennycode / tsconfig.json
Created January 24, 2024 11:08
CommonJS TS Config
{
"compilerOptions": {
// Code
"rootDir": "src", // ⟵ In
"outDir": "dist", // ⟵ Out
// Syntax
"lib": ["ES2022"], // ← In
"target": "ES2022", // ← Out
@bennycode
bennycode / commonjs.js
Created March 20, 2023 13:47
CommonJS
function add(a, b) {
return a + b;
}
exports.add = add;
function substract(a, b) {
return a - b;
}
@bennycode
bennycode / main.ts
Last active August 29, 2023 13:54
Better error handling with unknown type in TypeScript
const hasErrorCode = (error: unknown): error is { code: string } => {
return !!error && typeof error === 'object' && 'code' in error && typeof error.code === 'string';
};
try {
throw {code: 72};
} catch (error: unknown) {
if (hasErrorCode(error)) {
console.error(`Failed with error code "${error.code}".`);
}
@bennycode
bennycode / webpack.config.js
Created August 15, 2022 22:45
Multiple Webpack Output Libraries
module.exports = {
devtool: 'source-map',
entry: {
[projectName]: `${__dirname}/${pkg.main}`,
},
externals: {
dexie: 'Dexie',
},
mode: 'production',
output: {
@bennycode
bennycode / never.ts
Last active August 14, 2022 22:30
Never Type
interface StreamResponse {
status: StreamStatus;
}
enum StreamStatus {
IDLE,
ONLINE,
OFFLINE,
}
@bennycode
bennycode / Type-Guard.ts
Created August 11, 2022 09:49
Type Guard
type Dog = {
age: number;
name: string;
bark: () => void;
type: 'dog'
}
type Person = {
age: number;
name: string;
@bennycode
bennycode / generic-inheritance.ts
Created May 15, 2022 23:22
Generic Types and Inheritance in TypeScript
interface User {
name: string;
}
interface HappyUser extends User {
clap: () => void;
}
function printName<T extends User>(someone: T): T {
console.log(someone.name);
@bennycode
bennycode / generic-interface.ts
Created May 15, 2022 23:00
Generic interfaces in TypeScript
interface HttpResponse<T> {
code: number;
data: T;
}
interface ResponseData {
completed: boolean;
id: number;
title: string;
userId: number;
@bennycode
bennycode / multiple-generic-types.ts
Created May 15, 2022 22:58
Multiple generic types in TypeScript
function rollDice(array: any[]): number {
return Math.floor(Math.random() * array.length);
}
function getRandoms<A, B>(as: A[], bs: B[]): [A, B] {
const a = as[rollDice(as)];
const b = bs[rollDice(bs)];
return [a, b];
}
@bennycode
bennycode / generic-function.ts
Last active May 15, 2022 23:29
Generic Functions in TypeScript
function getRandom<T>(array: T[]): T {
const diceRoll = Math.floor(Math.random() * array.length);
return array[diceRoll];
}
const names = [
'Amelia', 'Ava', 'Benjamin', 'Charlotte', 'Elijah', 'Emma',
'Evelyn', 'Harper', 'Henry', 'Isabella', 'James', 'Liam', 'Lucas', 'Mia',
'Noah', 'Oliver', 'Olivia', 'Sofia', 'Theodore', 'William'
];