# 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 theshape
of thevalues
- just image as
key - value
, but u have torestrict
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 bestring
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
providesintersection
types that is mainly used tocombine
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 🤞