Skip to content

Instantly share code, notes, and snippets.

View balanza's full-sized avatar

Emanuele De Cupis balanza

View GitHub Profile
"scripts":{
"start": "http-server ./dist -p4000",
"build": "node ./bin/build.js"
}
@balanza
balanza / bash
Last active January 20, 2019 19:18
# install dependencies the first time
npm install less http-server handlebars
# build the website
npm run build
# serve files via http
npm start
pipelines:
default:
- step:
name: Build
image: node:10
script:
- npm install
- npm run build
artifacts:
- dist/**
@balanza
balanza / mobile.ts
Last active January 30, 2019 16:29
type Mobile {
confirmed: boolean,
value: string
}
type User {
/* name, surname, etc */
mobile: Mobile
}
type Valued<T> = { value: T }
type ConfirmedMobile = Valued<string> & { status: 'confirmed' }
type UnconfirmedMobile = Valued<string> & { status: 'unconfirmed' }
type Mobile = ConfirmedMobile | UnconfirmedMobile
type User {
/* name, surname, etc */
mobile: Mobile
}
// an user with confirmed mobile
// optimistic implementation: assume mobile.status will only have those two values
const printMobile = (mobile: Mobile) => {
if(mobile.status === 'confirmed') {
console.log('Your mobile is confirmed!')
} else {
console.warn('Your mobile is not confirmed!')
}
}
// defensive implementation: assume mobile.status can be whatever
// add this line
type CertifiedMobile = Valued<string> & { status: 'certified' }
// add CertifiedMobile to the unon type
type Mobile = ConfirmedMobile | UnconfirmedMobile | CertifiedMobile
const certified: CertifiedMobile = { status: 'certified', value: '543234531' }
printMobile(certified) // warn: Your mobile is not confirmed!
printMobileAlternative(certified) // unhandled exception: illegal state! mobile.status=certified
const exhaustionCheck = (e: never) => console.log('this will never be executed')
const printMobileSafe = (mobile: Mobile) => {
if(mobile.status === 'confirmed') {
console.log('Your mobile is confirmed!')
} else if(mobile.status === 'unconfirmed') {
console.warn('Your mobile is not confirmed!')
} else {
exhaustionCheck(mobile) // <-- you'll get a compilation error here!
}
type ConfirmedMobile = string
type UnconfirmedMobile = string
type CertifiedMobile = string
type Mobile = // just string :(
ConfirmedMobile
| UnconfirmedMobile
| CertifiedMobile