“This is the 8th day of my participation in the Gwen Challenge.

Interfaces in 1typeScript

One of the cores of TS is type checking of structured data. The interface is: abstract description of the state and behavior of the object methods. By default, the data type described by the interface must be satisfied, and the use of fields must be limited. Otherwise, an error will be reportedCopy the code
Define an interface to be used as a type in the Person object to qualify or constrain properties in the object. The first I stands for interface and the P stands for uppercase; IdCard read-only [readonly], age is numeric, sex is optional [?] [propN: string]: any Dynamically adds any fieldCopy the code
Interface IPerson{//idCard is a read-only property and cannot be modified. Readonly idCard: string, //age is mandatory age: number, // sex is an optional attribute sex? } const person: IPerson = {idCard:" IPerson ", age: 20, sex:' male ', weight:'200kg'} console.log(person)Copy the code

2 typeScript function types

Function type: used as a function type by calling the interface to find str2 in STR1; Return true if yes, false if noCopy the code
Interface ISearchHas {(str1:string,str2:string) :string ISearchHas {(str1:string,str2:string) : Boolean} // Define a function whose type is the interface defined above const lookforhas: ISearchHas = function(str1:string,str2:string) :boolean{ return str1.search(str2) > -1 } console.log(lookforhas("hello",'o')); //trueCopy the code

3. Array type restrictions

var arr: number[] = [1, 2, 3]; Var arr2: string[] = ["1", "2"]; Var arr3: any[] = [1, "2", true]; // An array of any typeCopy the code
Array<elemType> Specifies that the Array type is numeric. Var arr: Array<number> = [1, 2, 3]; console.log(arr); Var arr2: Array<any> = [1, true, "123"]; console.log(arr2);Copy the code

4 Return type of the function

Function person(name: string, age: number): number {return age; } var ageNum: number = person("zahngs", 10); console.log(ageNum);Copy the code
2. Surname parameter uncertain use may not have gender ha. function person2(name: string, sex? : string): string { return name; } var name2: string = person2(" ", ""); console.log(name2);Copy the code
Function person(name: string = "", age: number = 10): number {return age; } var p: number = person(); console.log(p);Copy the code