# 🐑 TypeScript Cheatsheep
TypeScript is a superset of JavaScript which specifies variables type, it catches errors before compiling. TS compiler (tsc) compiles .ts into .js.
###### tags: `🐑cheatsheep`
---
## Compile
Typescript compiler compiles ts into js, which browsers reads.
* generate a tsconfig.json
```clike
$ tsc --init
```
* modify the tsconfig.json
```json
"target": "es6"
"module": "es2015",
"rootDir": "./src", //where your src code comes
"outDir": "./public", //where you what your js to be
// add this to the bottom of this file
// tells tsc that only to compile the
// files inside the files which mentioned in this array
"include": ["src"]
```
* autocompile files into js. `-w` means watching.
```clike
$ tsc <filename.ts> -w
```
---
## Types
types of typescript:
* string
* number
* boolean
* object
* array(a kind of object)
* tuples
* function
* enum
* type alias/ interface
* class
* uinion
* any
you do not need to specify the type most of the time, tsc automatically determines that.
```typescript
const name = 'alan'
name = 10 //error
```
if you try to change the value of an variable into other type, it will error.
### Arrays
arrays has to be contained of only the types when initialized.
```typescript
let myArray = ['hello', 'alan', 10];
array.push(true) //error
```
* explicit type
```typescript
let mixedArray: (sting | number)[] = [];
```
### Objects
ths same
```typescript
let myObj = {
name: string,
age: number
}
myObj = {
name: 'alan',
age: 21,
gender: 'male' //error: can't add prop that is not init
}
myObj.name = true //error
```
### Any
you can declare a var to be `any` type.
```typescript
let name: any = 'alan';
```
and it can be changed to any type.
---
## Functions
```typescript
let greet: Function;
//note that it start with and capital F
greet = () => {
//...
}
//or function signature like below
let greet = (a: number, b: number) => number;
```
* optional input
```typescript!
//question mark for optional
const add = (a: number, b: number, c?: number | string) => {
//...
}
// or give it a default value
const add = (a: number, b: number, c: number | string = 5) => {
//...
}
```
* specifies the return type
```typescript!
const minus = (a: number, b: number): void => {
console.log(a - b)
}
```
---
## Type alias
declare types that are used often
```typescript!
type StringOrNum = string | number;
type objWithName = {name: string, uid: StringOrNum};
```
---
## Class
```typescript!
class Invoice {
client: string,
details: string,
amount: number
constructor(c: string, d: string, a: number){
this.client = c;
this.details = d;
this.amount = a;
}
}
```
* public, private, readonly
```typescript!
class Invoice {
// can only be coded like this when specifies public/private/readonly
constructor(
public c: string,
private d: string,
readonly a: number
){}
}
//typescript auto asign value for you
```
---
## Interface
interface is like a modifier of type
```typescript!
interface IsPerson {
name: string;
age: number;
speak(a: string): void;
}
const me: IsPerson = {
name: 'alan',
age: 21,
speak(text: string): void {
console.log(text);
}
}
```
> * [Difference between type alias and interface](https://levelup.gitconnected.com/typescript-what-is-the-difference-between-type-and-interface-9085b88ee531)
### with class
```typescript!
interface HasName {
name: string;
}
class Person implements HasName{
//Person needs to have a prop of name: string
//it can also have other props tho
}
```
### with variables
```typescript!
interface HasName {
name: string;
}
class Person implements HasName{
//...
}
//ensures that this clientOne is a var follows HasName
let clientOne: HasName;
clientOne = new Person(...)
```
---
## Generics
### with functions
If we do something like below it errors, because typescript doesn't know `name` property exist.
```typescript
const addUID = (obj: object) => {
let uid = randNum();
return {...obj, uid}
}
let doc = addUID({name: alan, age: 21});
console.log(doc.name) //error
```
we add an `<T>` at the front of a function, saying that it capture the type that inputs, and set it to `obj`.
```typescript
const addUID = <T>(obj: T) => {
//...
}
```
and it will do just fine.
* you can also add some restrictions to the type T:
```typescript
const addUID = <T extends {name: string}>(obj: T) => {
//...
}
```
### with interfaces
```typescript
interface Resource<T> {
uid: number,
name: string,
data: T
}
//specifies the type you want
const doc: Resource<string> = {
uid: 1,
name: 'alan'
data: 'hi alan'
}
```
---
## Enums
```typescript!
enum ResourceType { BOOK, MOVIE, CAT, DOG }
let resourceOne = ResourceType.CAT
//returns 2 so that you dont need to remember the number represents a specific type
```
---
## Tuples
a tuples is an array that is specified with types in it
```typescript!
let tup: [string, number] = ["alan", 21];
```
you can use it when your new a class, for ex:
```typescript!
class Human = {
constructor(
name: string,
age: number
){}
}
//if this line of code isnt coded, it errors
//tsc does not know what type of each prop is, but class Human specifies each prop
let props: [string, number];
props = [nameForm.value, ageForm.value];
let HumanOne = new Human(...props);
```
---
## Ref.
all from here:
* [NetNinja - TypeScript Tutorial](https://www.youtube.com/watch?v=fPYbNXzXP6M&list=PL4cUxeGkcC9gUgr39Q_yD6v-bSyMwKPUI&index=21&ab_channel=TheNetNinja)