Home

Awesome

Learning TypeScript

Just one of the things I'm learning. https://github.com/hchiam/learning

Static type checking. CLI tool to transpile to JavaScript that can run on older browsers too. Also can use constructor parameter public keyword as a shorthand to automatically add properties to a class. I think I really like the interface and enum part of TypeScript (e.g. as a consult-able in-code reference to help you/others remember what inputs to include or optionally have).

Why bother with types: For me, type checking is not only for preventing errors, but also to remind you of what data or functions you need to implement. It's like automatically-generated documentation.

Try it live in your browser

Official Website's Playground: https://www.typescriptlang.org/play/index.html

Try it locally with CLI

npm install -g typescript

and then

tsc code-to-compile.ts

or

tsc code-to-compile.ts --outDir output

or

tsc code-to-compile.ts --outFile output/output.js

More CLI transpiler options: https://www.typescriptlang.org/docs/handbook/compiler-options.html

Some notes on classes, interfaces, extends, implements, and abstract:

A YouTube Tutorial I'm Following

https://www.youtube.com/watch?v=WBPrJSw7yQA -> youtube-tutorial sub-folder.

# you should have tsc installed:
tsc --version
# transpile:
tsc main.ts --watch # or just: tsc main

And then you can stop and then run the compiled code in CLI:

# run js file:
node main.js
function getFullNameScalable(person: Person): string {
  return person.firstName + " " + person.lastName;
}
interface Person {
  firstName: string;
  middleName?: string; // optional
  lastName: string;
}
let person = {
  firstName: "Bruce",
  lastName: "Wayne",
};
console.log(getFullNameScalable(person));

(Aside: TypeScript defaults class members to public.)

TypeScript decorators

https://blog.logrocket.com/a-practical-guide-to-typescript-decorators/#:~:text=Automatic%20error%20guard

https://github.com/hchiam/learning-typescript/tree/master/decorator-example

interface vs type keywords

https://pawelgrzybek.com/typescript-interface-vs-type

How to use .d.ts files (type declaration files)

https://www.typescriptlang.org/docs/handbook/declaration-files/consumption.html

Type declaration files are what tells TS what types things have, to give you those helpful hover messages, autocomplete, etc.

Example: to get type declarations for node (if it doesn’t already come with its own type files bundled in):

npm install --save-dev @types/node

or https://github.com/bersling/typescript-library-starter (has example library and consumer)

Example .d.ts files for example .js files

https://www.typescriptlang.org/docs/handbook/declaration-files/templates/module-d-ts.html

More examples

https://github.com/hchiam/learning-js/tree/master/ts