TS STRUCTURE - Interfaces

2023-05-17 19:06:59 浏览数 (2)

# Interfaces

An interface is a declaration that is similar to a class but does not have a method implementation. You can use it to describe the properties and methods of objects.

At the same time, the interface does not have the implementation of functions and does not have the code itself – it is only necessary for the compiler to evaluate your implementations of the object (the class is also an object).

Roughly speaking, an interface is a descriptive structure. Unlike classes, interfaces are uncompilable and live only in TS runtime.

代码语言:javascript复制
interface IServer {
  hostname: string;
  location: string;
  active: boolean;
  public_addresses: string;
}

It is usually customary to say “implement the interface” rather than “use the interface” since the compiler verifies that the interface is implemented correctly. And, in case of an incorrect implementation (there is not at least one property), it will output errors every time you do something wrong.

You can use one interface as a type for a property of another interface.

代码语言:javascript复制
interface IPublicAddress {
  netmask: string;
  gateway: string;
  address: string;
}

interface IServer {
  hostname: string;
  location: string;
  active: boolean;
  public_addresses: IPublicAddress;
}

Note that in addition to primitive types and other interfaces, you can describe functions in interfaces.

代码语言:javascript复制
interface IServer {
  getPublicAddress(): () => IPublicAddress;
}

// specify the parameters of the function
interface ICalculator {
  sum: (a: number, b: number) => number;
}

# Extending Interfaces

In TS, you can only extend interfaces, not inherit them.The extension is used if you need a new interface to have not only all the properties of an interface, but also have additional or unique properties for that interface.

代码语言:javascript复制
interface IResponse {
  status: number;
}

interface ISlackResponse extends IResponse {
  ok: boolean;
}

# Indexed Types

Sometimes you may need to allow storing in an objectnot only a pre-known number of properties but also a variable, for example, when you implement the interfaceof a cache. In this case, you don’t know the name of the property, but you do know its type.

代码语言:javascript复制
interface ICache {
  size: number;
  first: ICacheItem;
  last: ICacheItem;
  items: {
    [item: string]: ICacheItem;
  }
}

Now you can write any value to the items object that has a string type key and an ICacheItem type value.

# Interfaces Implementation

代码语言:javascript复制
interface ICacheItem {
  mtime: number;
  content: string;
}

interface IFileCache {
  set: (key: string, value: ICacheItem) => void;
  get: (key: string) => ICacheItem;
}

class FileCache implements IFileCache {
  store = new Map();
  set (key: string, value: ICacheItem) {
    this.store.set(key, value);
  }
  get (key: string) {
    return this.store.get(key);
  }
}

0 人点赞