Typescript learning record interface

Attribute type interface

Interface describing object properties

On Interface

To restrict the properties of an object, you can use {} directly, but it is not convenient to reuse

	//Here {firstName: string} is used to restrict the type of name
    function printName(name: { firstName: string }) {
        console.info(name.firstName);
    }

    printName({ firstName: "Hello" });   //Correct
    // Printname ({firstname: "hello", LastName: "world"}) / / error reported
    var name1 = { firstName: "Hello", lastName: "World" };
    printName(name1);       //Correct

Use interface

This interface specifies that Name must have a firstName attribute of type string

    //Define an interface
    interface Name {
        firstName: string;
    }

    function printName1(name: Name) {
        console.info(name.firstName);
    }

    printName1({ firstName: "Hello" });   //Correct
    // Printname1 ({firstname: "hello", LastName: "world"}) / / error reported
    var name1 = { firstName: "Hello", lastName: "World" };
    printName1(name1);       //Correct

Interface optional properties

    interface Name {
        firstName: string;
        //? Indicates that the lastName property is optional
        lastName?: string;
    }

Read-only attribute

Can only be modified when an object is first created

The easiest way to decide whether to use readonly or const is to use it as a variable or as an attribute. Const is used as a variable, and readonly is used as an attribute.

interface Point {
    readonly x: number;
    readonly y: number;
}
let p1: Point = { x: 10, y: 20 };
p1.x = 5; // error!

Function type interface

An interface that describes a function type

    //Function type interface
    interface SearchFunc {
        //Note: there is no function keyword in function type interface
        (source: string, subString: string): boolean;
    }
    //Correct
    //For type checking of function types, the parameter name of a function does not need to match the name defined in the interface.
    let mySearch: SearchFunc = function (sou: string, sub: string) {
        return sou.search(sub) > -1;
    }
    // If you don't want to specify a type, TypeScript's type system infers the parameter type because the function is directly assigned to a SearchFunc type variable
    let mySearch1: SearchFunc = function (sou, sub) {
        return sou.search(sub) > -1
        ;
    }

Indexable interface

number index

Array constraint

    interface MyArr {
    	//Index is number and value is string
        [index: number]: string;
    }
    let arr: MyArr = ["1", "2"];

string index

Object constraint

    interface MyObj {
        [attr: string]: string;
    }
    let obj: MyObj = { 1: "1", a: "a" };

TypeScript supports two types of index signatures: string and number. You can use both types of indexes, but the return value of a numeric index must be a subtype of the return value type of a string index. This is because when you use number to index, JavaScript will convert it to string and then index the object. That is to say, using 100 (a number) to index is equivalent to using "100" (a string) to index, so the two need to be consistent.

Read-only index

Setting the index signature to read-only prevents the index from being assigned a value:

	interface ReadonlyStringArray {
	    readonly [index: number]: string;
	}
	let myArray: ReadonlyStringArray = ["Alice", "Bob"];
	myArray[2] = "Mallory"; // error!

Class type interface

Like the basic function of an interface in Java, TypeScript can explicitly enforce a class to conform to a contract.

	interface ClockInterface {
        currentTime: Date;
        setTime(d: Date): void;
    }

    class Clock implements ClockInterface {
        currentTime: Date;
        setTime(d: Date) {
            this.currentTime = d;
        }
        constructor(d: Date = new Date()) {
            this.currentTime = d;
        }
    }

Constructor interface

	//A is a constructor, not a parent of B
	interface A {
		//A parameterless constructor to create a B object
        new(): B;
    }

    class B {
        constructor() {}
        run(){
        }
    }
    //Assign the constructor of B to a0, and you can create a B object through a0
    //Unlike polymorphism, polymorphism is the assignment of a subclass instance to a parent class
    let a0:A = B;
    //Create the B object and execute the run method
    new a0().run();

Application of constructor interface

    interface ClockConstructor {
        new(hour: number, minute: number): ClockInterface1;
    }
    interface ClockInterface1 {
        tick(): void;
    }

    function createClock(ctor: ClockConstructor, hour: number, minute: number): ClockInterface1 {
        return new ctor(hour, minute);
    }

    class DigitalClock implements ClockInterface1 {
        currentTime: Date = new Date();
        constructor(h: number, m: number) { }
        tick() {
            console.log("beep beep");
        }
    }
    class AnalogClock implements ClockInterface1 {
        currentTime: Date = new Date();
        constructor(h: number, m: number) { }
        tick() {
            console.log("tick tock");
        }
    }

    let digital = createClock(DigitalClock, 12, 17);
    let analog = createClock(AnalogClock, 7, 32);

    digital.tick();
    analog.tick();

Inheritance interface

An interface can inherit multiple interfaces and create a composite interface of multiple interfaces

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;

Mixed type

An object can be used as both a function and an object with additional properties.

interface Counter {
	//Itself is a function
    (start: number): string;
    //Attribute
    interval: number;
    //There are ways
    reset(): void;
}

function getCounter(): Counter {
    let counter = <Counter>function (start: number) { };
    counter.interval = 123;
    counter.reset = function () { };
    return counter;
}

let c = getCounter();
c(10);	//c is a function that can be called (start: number): string;
c.reset();	//c has a reset method reset(): void;
c.interval = 5.0;	//Property interval: number;
58 original articles published, praised 4, visited 387
Private letter follow

Tags: Attribute TypeScript Javascript Java

Posted on Sun, 15 Mar 2020 02:43:53 -0700 by tbobker