Typescript – Cheat sheet (1)

How to use typescript in class?

class Greeter {
  greeting: string;

  constructor(message: string) {
    this.greeting = message;
  }

  greet() {
    return "Hello, " + this.greeting;
  }
}

let greeter = new Greeter("world");

What is the difference between ts and tsx files?

  • ts file doesn’t include jsx codes
  • tsx file include jsx codes

What is the difference between Interface vs Type?

They are similar, the following can be done by only Interface

Declaration merging

interface Song {
  artistName: string;
};

interface Song {
  songName: string;
};

// TypeScript automatically merges both interfaces declarations into one
// So when we use this Song interface, we’ll have both properties.
const song: Song = {
  artistName: "Freddie",
  songName: "The Chain"
};

Extends and implements

class Car {
  printCar = () => {
    console.log("this is my car")
  }
};

interface NewCar extends Car {
  name: string;
};

class NewestCar implements NewCar {
  name: "Car";
  constructor(engine:string) {
    this.name = name
  }
  printCar = () => {
    console.log("this is my car")
  }
};

When to use interface and type?

  • Use interface to define props that a specific component is going to receive
interface TodoProps {
  name: string;
  isCompleted: boolean
};

const Todo: React.FC<TodoProps> = ({ name, isCompleted }) => {
  ...
};
  • Types are better when you need to create functions
type Person = {
  name: string,
  age: number
};

type ReturnPerson = (
  person: Person
) => Person;

const returnPerson: ReturnPerson = (person) => {
  return person;
};

How to define a generic type?

  • You can migrate a function into typescript function like this
function identity(value) {
  return value;
}

const result = identity(123);
// Definition
function identity<T>(value: T): T {
  return value;
}

// Usage
const result = identity({ age: 123 });
// or
// const result = identity<{ age: number }>({ age: 123 });

This means function accepts the generic type parameter T. This type is the first argument type. Then set the return type to be the same with : T.

  • Then, you can pass type parameter like this
function identity<T>(value: T): T {
  return value;
}

type ProgrammingLanguage = {
  age: number;
};

/* Case 1: Pass type paramater */
const result = identity<ProgrammingLanguage>({ age: 123 });
// result has custom type as ProgrammingLanguage

/* Case 2: Don't pass type paramater */
const result = identity({ age: 123 });
// result has type as { age: number }
  • Look at your function, you’ll see generic is not being used in the argument list or any other place that TypeScript would be able to infer its value.
    This means that the calling code must explicitly pass a type for this generic when calling your function like this const result = identity<ProgrammingLanguage>({ age: 123 });

Be the first to comment

Leave a Reply

Your email address will not be published.


*