[Distinguish] Typescript the interface and type

During the contact ts related code, and interface type you can always see the figure. Just remember, do not know when consulted have encountered type, remember that they like, with the same function which can be achieved. But recently always see them, want in-depth look at them.

interface: Interface

Is one of the core principles TypeScript values ​​has a structure type checking. The role of the interface is named and your code or third-party code is defined for these types of contracts.

interface LabelledValue {
  label: string;
}

function printLabel(labelledObj: LabelledValue) {
  console.log(labelledObj.label);
}

let myObj = {size: 10, label: "Size 10 Object"};
printLabel(myObj);

An interface like a name used to describe the example above requirements.

Interface has the characteristics:

  • Optional attributes
interface SquareConfig {
  color?: string;
}
  • Read-only attribute
interface Point {
    readonly x: number;
}
  • Excess property checks to prevent the use of the properties of the interface does not belong to
interface Preson {
    name: string;
    age?: number;
}

let p1:Person = {name: '小明'} // 正确
let p2:Person = {name: '小明', age: 18, sex: '男'}; // 报错

// 绕过:多余属性不报错
// 方式1 
let p = {name: '小明', age: 18, sex: '男'};
let p3 = p;

// 方式2
interface Preson {
    name: string;
    age?: number;
    [propName: string]: any
}
let p4 = {name: '小明', age: 18, sex: '男'};
  • Function Type
interface SearchFunc {
  (source: string, subString: string): boolean;
}
  • Index types: for arrays
interface StringArray {
  [index: number]: string;
}

let myArray: StringArray;
myArray = ["Bob", "Fred"];
  • Class Type
    • Class implements the interface
    interface ClockInterface {
      currentTime: Date;
      setTime(d: Date);
    }
    
    class Clock implements ClockInterface {
      currentTime: Date;
      setTime(d: Date) {
          this.currentTime = d;
      }
      constructor(h: number, m: number) { }
    }
    • Interface inheritance interface, more
    interface Shape {
    color: string;
    }
    
    interface PenStroke {
        penWidth: number;
    }
    
    interface Square extends Shape, PenStroke {
        sideLength: number;
    }
    
    let square = <Square>{};
    square.color = "blue";
    square.sideLength = 10;
    square.penWidth = 5.0;

type: type alias

type will give a new name from a type. type and sometimes like interface, but can be applied to the original value (basic type), union types, tuples and anything else you need to type handwritten.

For example:

type Name = string; // 基本类型
type NameResolver = () => string; // 函数
type NameOrResolver = Name | NameResolver; // 联合类型

function getName(n: NameOrResolver): Name {
    if (typeof n === 'string') {
        return n;
    } else {
        return n();
    }
}

Since the alias will not create a new type - it creates a new name to refer to that type. To the basic types of aliases are usually useless, although you can use as a form of documentation.

Like the interface, type alias may be generic - and we can add the type parameter passed to the right of the alias declaration:

type Container<T> = { value: T };

You can also use an alias to refer to its own type in the property:

type Tree<T> = {
    value: T;
    left: Tree<T>;
    right: Tree<T>;
}

Used with cross type, we can create some very strange type.

type LinkedList<T> = T & { next: LinkedList<T> };

interface Person {
    name: string;
}

var people: LinkedList<Person>;
var s = people.name;
var s = people.next.name;
var s = people.next.next.name;
var s = people.next.next.next.name;

However, the type of alias can not appear anywhere on the right side of the statement.

type Yikes = Array<Yikes>; // error

interface vs type

1. Objects / Functions

Both can be used to describe the type of object or function, but the syntax.

Interface

interface Point {
  x: number;
  y: number;
}

interface SetPoint {
  (x: number, y: number): void;
}

Type alias

type Point = {
  x: number;
  y: number;
};

type SetPoint = (x: number, y: number) => void;

2. Other Types

And different interfaces, may also be used for other types alias types, such as the basic type (raw value), a joint type, a tuple.

// primitive
type Name = string;

// object
type PartialPointX = { x: number; };
type PartialPointY = { y: number; };

// union
type PartialPoint = PartialPointX | PartialPointY;

// tuple
type Data = [number, string];

// dom
let div = document.createElement('div');
type B = typeof div;

3. Extend

Both can be extended, but the syntax is different again. Also, note that the interface types and aliases are not mutually exclusive. Interface type aliases can be extended, and vice versa.

Interface extends interface

interface PartialPointX { x: number; }
interface Point extends PartialPointX { y: number; }

Type alias extends type alias

type PartialPointX = { x: number; };
type Point = PartialPointX & { y: number; };

Interface extends type alias

type PartialPointX = { x: number; };
interface Point extends PartialPointX { y: number; }

Type alias extends interface

interface PartialPointX { x: number; }
type Point = PartialPointX & { y: number; };

4. class Implements

Class can implement the interface type or alias in the same manner. Note, however, classes and interfaces are considered to be static. Therefore, they can not achieve / type of expansion joint type an alias name.

interface Point {
  x: number;
  y: number;
}

class SomePoint implements Point {
  x: 1;
  y: 2;
}

type Point2 = {
  x: number;
  y: number;
};

class SomePoint2 implements Point2 {
  x: 1;
  y: 2;
}

type PartialPoint = { x: number; } | { y: number; };

// FIXME: can not implement a union type
class SomePartialPoint implements PartialPoint {
  x: 1;
  y: 2;
}

5. extends class

Class definition will create two things: the instance of the class type and a constructor. Because you can create a class type, so you can use the interface to allow the use of local classes.

class Point {
    x: number;
    y: number;
}

interface Point3d extends Point {
    z: number;
}

6. Declaration merging

And different types of aliases, the interface can be defined many times, and will be treated as a single interface (all members of the combined declaration).

// These two declarations become:
// interface Point { x: number; y: number; }
interface Point { x: number; }
interface Point { y: number; }

const point: Point = { x: 1, y: 2 };

7. Calculate property, to generate a map type

type in a keyword can be used to generate a map type, but the interface does not work.

Grammar and syntax type index signature, internal use for .. in. It has three parts:

  • Type variable K, which in turn bind to each property.
  • String literal combined Keys, which contains a collection of attributes names to iterate.
  • Property result type.
type Keys = "firstname" | "surname"

type DudeType = {
  [key in Keys]: string
}

const test: DudeType = {
  firstname: "Pawel",
  surname: "Grzybek"
}

// 报错
//interface DudeType2 {
//  [key in keys]: string
//}

7. Other details

export default interface Config {
  name: string
}

// export default type Config1 = {
//   name: string
// }
// 会报错

type Config2 = {
    name: string
}
export default Config2

to sum up

interface and type like a lot of scenes, both can be used. But there are subtle differences:

  • Type: two objects, functions are applicable, but the type can be used for basic types, union types, Ganso.
  • Merge same name: interface support, type is not supported.
  • Calculation of property: type support, interface is not supported.

In general, use common interface to achieve, can not be achieved with the interface and then type implementation. The main project is a consistent best.

reference:

Guess you like

Origin www.cnblogs.com/EnSnail/p/11233592.html