This is the 14th day of my participation in the August More Text Challenge. For details, see:August is more challenging
Interfaces in Typescript
- In object-oriented programming, an interface is a specification that defines behavior and actions. In programming, an interface serves as a limitation and specification. An interface defines the specification that a class needs to follow. The interface does not care about the internal state data of the class, nor does it care about the implementation details of the methods in the class. Interfaces in typescrip are similar to Java, but with the addition of more flexible interface types, including properties, functions, indexables, and classes
Attribute class interface
interface ObjInfo { readonly name:string, age:number, hobby? PropName :string, [propName: string]: any; } let student:ObjInfo = {name:" ", age: 4}Copy the code
name
The type ofstring
.age
A type ofnumber
If the type is different, an error will be reportedhobby
Is an optional parameter that defines the interface for the optional attribute. symbol- The type checker does not check the order of the properties, as long as the corresponding properties exist and the type is correct
- Additional attribute check [propName: string]: any
- Read-only attribute: the interface that defines the read-only attribute. You only need to add readonly before the name of the read-only attribute
Function type interface
interface Info{ (name:string,age:number):string } let student:Info = function (name:string,age:number):string{ return ` I is ${name}, I ${age} - year - old `} the console. The log (student (' pig small fart, 5))Copy the code
Indexable interface
- In this interface, we can set the index value and element of an array to different types. The index value can be a number or a string.
Interface namelist {[index:number]:string} let namelist:namelist = [' namelist ',' namelist ', 1] error element 1 is not a stringCopy the code
[index:number]
The subscript fornumber
Type, the value isstring
Class type interface
interface Animal{ name:string; eat(str:string):void; } class Pig implements Animal{ name:string constructor(name:string){ this.name = name } eat(str:string):void{ Log (' ${name} eat ${STR} ')}} let pig = new pig (' ${name} ') console.log(' ${name} eat ') console.log(' ${name} eat ')Copy the code
- Let a class implement an interface; Note, however, that the interface describes the public part of the class, not the public and private parts, so there is no check to see if the class has any private members