62 lines
1.2 KiB
Markdown
62 lines
1.2 KiB
Markdown
# Interfaces in TypeScript
|
|
|
|
[Handbook](https://www.typescriptlang.org/docs/handbook/interfaces.html)
|
|
|
|
## Overview
|
|
|
|
Interface in TypeScripts are used to create a _blueprint_ or an abstraction of a class.
|
|
|
|
An interface can contains properties (_mandatory_, _optional_ or _readonly_)
|
|
|
|
```typescript
|
|
interface Example {
|
|
mandatory: string;
|
|
optional?: string;
|
|
readonly ro: string;
|
|
}
|
|
```
|
|
|
|
And methods
|
|
|
|
```typescript
|
|
interface Example {
|
|
mandatory: string;
|
|
optional?: string;
|
|
|
|
concat(sep: string): string;
|
|
}
|
|
```
|
|
|
|
To use the interface, a class should **implement** it,
|
|
|
|
```typescript
|
|
class Impl implements Example {
|
|
mandatory: string;
|
|
optional?: string;
|
|
|
|
constructor(m: string, o: string) {
|
|
this.mandatory = m;
|
|
this.optional = o;
|
|
}
|
|
|
|
contact(sep: string): string {
|
|
return `${this.mandatory}${sep}${this.optional}`;
|
|
}
|
|
}
|
|
```
|
|
|
|
## The Promise case
|
|
|
|
What about a promise based method ? Do not forget what async/await does. It wraps all the things in `Promise<T>`.
|
|
|
|
In order to add promise to your interface, just specify a Promise as return type.
|
|
|
|
```typescript
|
|
interface Example {
|
|
mandatory: string;
|
|
optional?: string;
|
|
|
|
promize(arg: string): Promise<string>;
|
|
}
|
|
```
|