#webdev #javascript #typescript
December 4, 2024 @ 05:36
[Perplexity Thread](https://www.perplexity.ai/search/what-is-an-interface-in-javasc-qN83LJC9QG2Ekw7sZGdGPQ)
# Interfaces
**Interfaces** exist in Typescript to improve type safety and code readability by ensuring that objects adhere to a specified structure by specifying what properties and methods the object should have. Interfaces allow you to define the expected properties and methods of an object without implementing them.
**For example:**
```typescript
interface IPerson {
firstName: string;
lastName: string;
sayHi () => string;
}
```
**Interfaces** can also specify **optional properties** by using a question mark `?` and **read-only properties**, which cannot be modified after assignment.
```typescript
interface ICar {
readonly brand: string;
model?: string;
}
```
**Function Interfaces** can be used to specify parameter types and return types to ensure that functions adhere to specific signatures.
```typescript
interface Calculator {
(a: number, b: number): number;
}
// add must take 2 numbers and return number, per the interface
const add: Calculator = (a, b) => a + b;
```
**Interface inheritance** is possible, allowing you to create complex types from simpler ones and promoting code reuse and modularity.
```typescript
interface Shape {
color: string;
}
// Circle has properties 'color' AND 'radius'
interface Circle extends Shape {
radius: number;
}
```
# Interfaces vs Types
> [!warning]
> I got tired and stopped, but there are fundamental differences here that I need to read from the Perplexity search and type here after understanding.
In short:
- You can define multiple interfaces with the same name, and one interface will be created merging all of the properties and methods--called **declaration merging**. Once a type is defined, conversely, it cannot be changed outside of its declaration (it is thus inherently more primitive).
- And a few other differences . . .