Skip to content

Instantly share code, notes, and snippets.

@RoyalIcing
Last active November 18, 2022 05:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RoyalIcing/56caf35b6e9ee0b9f6b131758bcd3c57 to your computer and use it in GitHub Desktop.
Save RoyalIcing/56caf35b6e9ee0b9f6b131758bcd3c57 to your computer and use it in GitHub Desktop.
JavaScript and TypeScript: two worlds run at different times
// Constants are values with names.
// Functions accept values and return values.
const favoriteNumber = 7
const favoriteNumber2 = (n: number) => n * 2
const doubleNumber = (n: number) => n * 2
const a = doubleNumber(favoriteNumber)
// = 14
// Types are value specifications with names.
// Generic types accept types and return types.
type FavoriteNumber = 7
type DualNumber<N extends number> = [N, N]
type A = DualNumber<FavoriteNumber>
// = [7, 7]
// TypeScript is a blend of JavaScript and types.
// It’s really two languages that execute at different times.
// The JavaScript executes at run time. If something goes wrong, it’s a runtime exception or bug.
// The TypeScript executes at compile time. If something goes wrong, it’s a compiler error.
// Ideally the validation that every type is right at compile time, leads to fewer errors occuring at runtime.
// In TypeScript, every constant, variable, function, and class have a corresponding type.
// The two languages are sewn together.
const z: number = 9
// Generics help with this tapestry, by allowing the types to flexibly adapt to the current scenario.
// Just like a function that doubles numbers doesn’t need to know in advance every single possible number that
// could ever be passed to it as a parameter, a generic type doesn’t need to know in advance every single type
// that could ever be passed it as a parameter.
// The doubleNumber(n) function spits out a new value, based on the number that was passed as a parameter.
// The DualNumber<N> generic type spits out a new type, based on the type that was passed as a parameter.
// You’ll notice that these two have a lot of similarities, just different syntax:
// const doubleNumber = (n: number) => …
// type DualNumber<N extends number> = …
// Just like Functions allow our programs to vary and adapt when executing at runtime,
// Generic types allow our programs to vary and adapt when executing at compile time.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment