Denny Chang
Contact
  • Theme Mode

  • Language

Typescript Notes Part 2
Typescript Notes Part 2the image is from google

Typescript Notes Part 2

if you miss last notes, click here let's keep going

Functions

  • callable types
// type alias:
type CallTypes = (a: number, b: number) => number;

// interfaces:
interface CallTypes {
  (a: number, b: number): number;
}

if function is not return anything, type will be void

Function overloads

It's one that not is javascript Sometimes we might use same function with different parameter amounts for example,

// overloads signature
function transformDate(timestamp: number): Date
function transformDate(y:number, m:number, d: number): Date
// implementation signature
function transformDate(timestampOrYear: number, m?:number, d?:number): Date{
  if(!m && !d){
    return new Date(timestampOrYear)
  }else {
    return new Date(timestampOrYear,y,d)
  }
}

// then when you use function like
transform(2022,12)
// will throw an Error tell you that function accept 1 or 3 parameters
...

Classes

Access modifier keywords

  • public (as default)
  • protected (allow instance itself and its subclasses)
  • private (allow instance itself only, can also use symbol "#")
...

Top and bottom types

  • top type any possible value that allowed by system: any | unknown

difference between any and unknown : unknown can not use without first applying a type guard

  • bottom type means no possible value that allowed by the system: never
...

type guards and narrowing

basic type guards are: typeof, instanceof

Nullish values

  • null : there is a value, and value is nothing

  • undefined : values is not available yet

  • void : function return should be ignore

...

Generics

Generics allow us to parameterized types, making types can be reused Typically, using as type params

usage:

// normal function
function wrapInArray(arg: string): string[] {
  return [arg];
}

// with generic
function wrapInArray<T>(arg: T): T[] {
  return [arg];
}

Try this exam by click the corner "Try"

Generic Constraints

We can use some constraints to types, so that make sure that type will have the properties/content that we need By using "extends" in generic

interface HasId {
  id: string;
}
function listToDict<T extends HasId>(list: T[]): Dict<T> {
  const dict: Dict<T> = {};

  list.forEach((item) => {
    dict[item.id] = item;
  });

  return dict;
}
// T extends HasId make sure that T at least is HasId

Conclusion: Typescript is helpful for you to find out some errors earlier yet, it's a little bit hard to learn, such as "Generics" But I think it's a worthy stuff to learn So... keep on it! Above notes are my study notes If there is any mistake, or any ambiguous, bear with me 🙏 I'll keep learning

this is today's sharing 👋