DanKim0213 / Today-I-Learned

Today I Learned
1 stars 0 forks source link

TypeScript #23

Open DanKim0213 opened 11 months ago

DanKim0213 commented 11 months ago

TypeScript

DanKim0213 commented 11 months ago

Why TypeScript is structurally typed type system.

As I wrote in the cheatsheet of typescript, the below example works just as if we had used an anonymous object type.

interface Point {
    x: number;
    y: number;
}

function printCoord(pt: Point) {
    console.log("The coordinate's x value is " + pt.x);
    console.log("The coordinate's y value is " + pt.y);
}

printCoord({ x: 100, y: 100 });

Another example is that when we narrow types:

type Fish = { swim: () => void };
type Bird = { fly: () => void };
declare function getSmallPet(): Fish | Bird;

function isFish(pet: Fish | Bird): pet is Fish {
  return 'swim' in pet;
}
// ---cut---
// Both calls to 'swim' and 'fly' are now okay.
let pet = getSmallPet()

// **Fish or Bird**
if (isFish(pet)) {
  pet.swim(); // Fish
} else {
  pet.fly(); // Bird
}

We can figure out which type of pet is by in operator.

Keep in mind that these three JavaScript operators:

DanKim0213 commented 11 months ago

Typescript Exercises

1. Objects

2. Union types

3. Narrowing

4. Utility types

5. Function overloads

6. Generics

Questions

Q. Why is Type Guard needed instead of intanceof?

Q. Is type Indexing possible with interfaces?

Q. which one between Type and Interface should I use since they are interchangeable?

You should consider consistency and augmentation. - Effective Typescript, item 13

If you are working in a codebase that consistently uses interface, stick with interface. The same goes for Type.

Else:

Q. (s: string | null) => void vs (s?: string) => void

A. Same