Skip to content

Instantly share code, notes, and snippets.

@sewera
Last active March 10, 2022 09:23
Show Gist options
  • Save sewera/65353ef8bdec440bb26f59a9c34333cd to your computer and use it in GitHub Desktop.
Save sewera/65353ef8bdec440bb26f59a9c34333cd to your computer and use it in GitHub Desktop.
"Dev vs production type checking" rewrite in TypeScript
// Based on: https://gist.github.com/ericelliott/e2dd9cbe5c64e44d6122ba76ec7dbf55#file-dev-vs-production-type-checking-js
type Timestamp = number // Date.now() returns number, so type alias gives better documentation
// good type names provide good documentation
type Employee = {
name: string,
hireDate?: Timestamp,
title?: string,
}
const createEmployee = (e: Employee): Employee => ({
name: e.name,
hireDate: e.hireDate ?? Date.now(),
title: e.title ?? 'Worker Drone',
})
// if the default values could be undefined (TS always errors when there is unchecked access to optional property),
// this function can be even simpler
const ce = (e: Employee): Employee => e
// if there are multiple functions with the same type signature, we can make a type for them
type EmployeeCreator = (e: Employee) => Employee
const c: EmployeeCreator = e => e
// In development, a framework doesn't have to wrap calls:
const emp1 = createEmployee({ name: 'foo' }) // works
const emp2 = createEmployee() // fails
// ^^^^^^^^^^^^^^^^
// Expected 1 arguments, but got 0. ts(2554)
const emp3 = createEmployee({ name: 1 }) // fails, but would pass in the js example
// ^^^^
// Type 'number' is not assignable to type 'string'. ts(2322)
// Call the function directly everywhere
const emp4 = createEmployee({ name: 'foo' })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment