# Object Types 🤞

TIP

In TypeScript, we group and pass around data is through object types but not objects (JS)

// anonymous
function greet(person: { name: string; age: number }) {
  return "Hello " + person.name;
}
// interface
interface Person {
  name: string;
  age: number;
}
// type alias
type Person = {
  name: string;
  age: number;
};
 
function greet(person: Person) {
  return "Hello " + person.name;
}

... skip for properties readonly and optional, I believe u have already understand them through their names

# Index Signatures

  • Sometimes you don’t know all the names of a type’s properties ahead of time, but you do know the shape of the values
  • just image as key - value , but u have to restrict your object elements as a key
  • Support-typescript-index-signature
type foot = { 
  [shot: string]: string 
};
const shot: foot = {
    'name': 'john',
    'email': 1231    // Error
}
  • An index signature parameter type must be string number symbol or a template literal type
  • Finally, you can make index signatures readonly in order to prevent assignment to their indices
interface ReadonlyStringArray {
  readonly [index: number]: string;
}
 
let myArray: ReadonlyStringArray = getReadOnlyStringArray();
myArray[2] = "Mallory";
Index signature in type 'ReadonlyStringArray' only permits reading.

# Extending Types

  • extends
interface Basic {
  ...
}
interface With {
  ...
}
interface With extends others, Basic {
  unit: string;
}

# Intersection& Types

  • TypeScript provides intersection types that is mainly used to combine existing object types
interface Colorful {
  color: string;
}
interface Circle {
  radius: number;
}
type ColorfulCircle = Colorful & Circle;

# Generic Object Types

  • <T>
interface Box<Type> {
  contents: Type;
}

happy coding 🤞

Last Updated: 2021/11/15 下午3:11:34