Skip to content

Instantly share code, notes, and snippets.

View maddymanu's full-sized avatar

Aditya Bansal maddymanu

  • Cortex (YC W20)
  • San Francisco
View GitHub Profile
@maddymanu
maddymanu / unionsIntro.ts
Created May 2, 2020 19:25
Simple Unions Example
// Introduction
type Human = {
name: string,
age: number
}
type Alien = {
name: string,
planet: string
}
@maddymanu
maddymanu / unionsPracticalEg.ts
Created May 2, 2020 19:24
Practical Example of Unions
// Practical example
//https://www.typescriptlang.org/docs/handbook/advanced-types.html#union-types
function padLeft(value: string, padding: string | number) {
if (typeof padding === "number") {
return Array(padding + 1).join(" ") + value;
}
if (typeof padding === "string") {
return padding + value;
}
throw new Error(`Expected string or number, got '${padding}'.`);
//Discriminated Unions
type Human2 = {
kind: 'human',
name: string,
age: number,
}
type Alien2 = {
kind: 'alien',
name: string,
@maddymanu
maddymanu / ds4.ts
Created May 2, 2020 19:09
Discriminated Unions Exhaustive Error Check
type InternalError = {
kind: 'internalerror',
error: string,
details?: string[]
}
type BadDataError = {
kind: 'baddata',
error: string,
data: any
@maddymanu
maddymanu / ds3.ts
Last active June 10, 2020 02:09
Discriminated Unions in TypeScript
type Human2 = {
kind: 'human',
name: string,
age: number,
}
type Alien2 = {
kind: 'alien',
name: string,
planet: string
@maddymanu
maddymanu / ds2.js
Last active May 2, 2020 19:19
Generated JavaScript for Simple TypeScript Discriminated Unions
"use strict";
function sayHello2(named) {
switch (named.kind) {
case "human":
console.log(`Hi ${named.name}`);
break;
case 'alien':
console.log(`Hi ${named.name} from ${named.planet}`);
break;
}