# Interface

* Defines a “shape” for JavaScript objects, functions and more
* Creates a contract for code

## Basic Interfaces

Basic interfaces in TypeScript are for the type Object

```javascript
interface XYZ {
    name: string;
    color: string;    
}

var summer : XYZ = {name:”Summer”,color:”Brown”} // ok
var lady : XYZ = {name:”Lady”} // throws error. Missing property “color”
var ghost : XYZ = {name:”Ghost”,color:”white”,silent:true} // throws error. XYZ has no property silent.
```

## Optional Properties

Interfaces can have optional properties

```javascript
interface Stark {
    name: string;
    location? : string;    
}

var bran : Stark = {name: “Bran”,location:”Summer”} // OK
var sansa : Stark = {name: “Sansa”} // Also OK. Direwolf property is optional.
```

## Function types

Interfaces can describe Functions as well

```javascript
interface Salute {
    (name: string) : string;
}

var bonjour : Salute= function(n : string) : string { return “Bonjour, “ + name };
```

## Array Types

* Interface can define both the kind of key an array uses and the type of entry it contains&#x20;
* Index can be of type string or type number

```javascript
interface NameList {
    [index: number]: string;
}
var list2 : NameList = ['Hemant',1,"Singh"] // error. 1 is not type string

interface Ages {
    [index: string]: number;
}
var ages: Ages = []; ages['Hemant'] = 15; // ok; ages[2] = ‘nine’; // error
```

## Class Types

* Interfaces can define a class similar to Java&#x20;

```javascript
interface Person {
    age: number;
}

class Stark implements Person {
    age: number;
    location: string;
}
```

## Extending Interfaces

Interfaces can extend other interfaces

```javascript
interface Person {
    age: number;
}

interface Musician extends Person { instrument: string; }

var s: Musician = { age: 20, instrument: 'Papa' };

console.log(s);
```

## Hybrid Interfaces

TypeScript interfaces can describe something that is a function and an object at the same time. Because, JavaScript!

```javascript
Interface Jump {
    (distance: number) : string;
    height: number;
}

var j : Jump;
j(50);
j.height = 12;
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://hemantajax-2.gitbook.io/javascript-step-by-step/interface.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
