Interface in 03ts

Keywords: Javascript TypeScript Vue.js ts

1, Object type

object represents a non primitive type, that is, a type other than number, string, boolean, symbol, null or undefined. object types can take several forms:

  • object type
  • Array type
  • Class type
  • Function type

These forms are called object types in TypeScript.

1. Object type:

For example, we write an object that represents the basic information of a commodity:

const KFC = {
    name: "Hamburger fried chicken",
    price: 38.5,
    sell() {
        return `Item is:${this.name},The selling price is:{this.price},Give me a coke!`
    }
}

//You can add a type annotation to this object
const KFC:{
    name: string;
    price: number;
    sell:() => string
}={
    name: "Hamburger fried chicken",
    price: 38.5,
    sell() {
        return `Item is:${this.name},The selling price is:${this.price},Give me a coke!`
    }
}
console.log(KFC.sell())

(1) Object annotation

We talked about type annotation before. Now we can also make a type annotation for objects.

Before using the object, we can design the structure of the object in advance according to the needs, that is, we establish a contract to restrict the structure of the object before defining the object.

For example, we create an object that contains the product name and price. We can constrain objects:

//The structured type of an object imposes type constraints on the structure of the object's value.
var  milkTea:{
    name: string;
    price:number;
    sell: () => string
}
 milkTea= {
    name: "Snow top Jasmine milk tea",
    price: 27,
    sell: function () {
        return `category:${this.name},Price:${this.price},Buy one get one free!`
    }
}

console.log(milkTea.sell());
//The syntax of an object type annotation is similar to that of the object itself.
//Note: multiple key value pairs are separated by semicolons (;), and semicolons can be omitted.

Question: how to add type annotations to methods in objects?

let people: {
    sayHi: () => void
    sing: (name: string) => void
    sum: (num1: number, num2: number) => number
    }

Key points of method type annotation: 1 Parameter 2 return value.
The contents in the parentheses to the left of the arrow (= >): indicates the parameter type of the method.
The content to the right of the arrow (= >): indicates the return value type of the method.

Disadvantages of writing type annotations directly after object names: 1. The code structure is not concise. 2. Type annotations cannot be reused.

2, Interface in ts

Interface: name the type annotation of the object and establish a contract for your code to constrain the structure of the object.

Syntax:

interface goodsFood {
    name: string;
    price: number;
    like: string;
    sell:()=>string
}


const coffe: goodsFood={
    name:"Raw coconut Latte",
    price:38,
    like:"Semi sugar,Warm",
    sell:function(){
        return `What do you want:${this.name},The current price is:${this.price},Preferences are:${this.like}`
        
    }
}
console.log(coffe.sell());
          

Function of interface: in object-oriented programming, interface is a normative definition, which defines the norms of behavior and action. In programming, interface plays a role of restriction and specification. The interface defines the specifications that a batch of classes need to comply with. The interface does not care about the internal state data of these classes or the implementation details of the methods in these classes. It only stipulates that some methods must be provided in this batch of classes, and the classes that provide these methods can meet the actual needs. The interface in typescrip t is similar to java, and more flexible interface types are added, including attributes, functions, indexable and classes.

(2) Attribute interface

Now let's define a method printPerson, a custom method that passes in parameters to constrain json

 function student(name:{ name: string }) {
    return `this is ${name.name}`
}

console.log(student({ name: "Lau Andy" })) 
 
function teacher(params: {name:string}) {
return `This is a teacher whose name is ${params.name}`
    
}

console.log(teacher({ name: "lemo" }));

At this time, we find that the constraints of the two methods on parameters are almost the same, so it is cumbersome to write them again every time. We can use the interface to constrain the parameters passed in by batch methods.

At this time, we can rewrite it into the following code:

interface label {
    name:string
}
function student(name:label) {
    return `this is ${name.name}`
}

console.log(student({ name: "Lau Andy" })) 
 
function teacher(params: label) {
return `This is a teacher whose name is ${params.name}`
    
}

console.log(teacher({ name: "lemo" }));

The attribute constraint on the incoming object is the attribute interface

Optional properties:

When passing parameters, if the current parameter is not a required option, it can be used as an optional parameter. Use? express

 interface mobile{
    name: string; //be careful; end
    price: number;
    color?: string; Optional attribute, which can not be passed when passing parameters
    size:string;
}

const iphone: mobile = {
    name: "iphone13pro",
    price: 7899,
    size: "4.7 inch",
    color:"red"
    
}

console.log(iphone);

(3) Function type interface

Constrain the parameters passed in by the method and the return value

interface fullName {
   (firstName:string,lastName:string):string
}

var person: fullName = (firstName: string, lastName: string) => `My name is ${firstName + lastName}`;

console.log(person("Spell","much"))

(4) Indexable interface

Array, object constraints

/**
 * Use interfaces to constrain arrays
 */
 
 interface arr {
  //The array index is of type number and the value is of type string
    [index: number]: string;
}

const menu: arr = ["Spareribs with brown sauce", "Yu-Shiang Shredded Pork", "Sauteed Abalone with Scallion"];
console.log(menu);

/**
 * Use interfaces to constrain objects
 */

interface fruit {
    [index: string]: string;
}

const mango = {
    name: "Fresh big mango",
    color: "yellow"
}

(5) Class type interface

Constraints on classes are somewhat similar to abstract classes

/**
 * Class type interface
 * Constraints on classes
 */
 interface Animal {
    name: string;
    age: number;
    eat(food:string):void
}

class Dog implements Animal {
    name: string;
    age: number;
    constructor(name: string, age: number) {
        this.name = name;
        this.age = age;
    }
    eat(food: string): void {
        console.log(`This puppy is ${this.name},Age:${this.age}year,I am eating ${food}`)
    }
}

const dog1 = new Dog("Cuihua", 2);
dog1.eat("Dog food!!");

(6) Interface expansion

Interfaces can inherit interfaces

/**
 * Interface expansion
 * Interface inheritance
 */

interface Animal{
    eat():void
}

interface Play extends Animal{
    play():void;
}

class Dogs implements Play{
    name:string;
    constructor(name:string){
        this.name = name;
    }

    eat(){
        console.log(this.name + 'I like eating bones')
    }

    play(){
        console.log(this.name + 'I like to dismantle things')
    }
}

var alpha = new Dogs('Erha')

alpha.eat();
alpha.play();

Posted by maliskoleather on Sat, 06 Nov 2021 09:18:59 -0700