<TypeScript>interface syntax and function interface---------Code analysis, clear and easy to understand

Table of contents

1. The interface describes the shape of the object

1. Syntax of interface

2. Optional attributes

3. Read-only attributes

4. How to write optional read-only attributes

5. Type description of the object’s attribute name

2. Function interface

a.Function

1. The syntax of functions in ts (defining types for functions)

2. Optional parameters

3.Default parameters 

4.Remaining parameters 

5. Variables of function type

 b.Function interface


1. The interface describes the shape of the object

1. Syntax of interface

        One of the core principles of TS is type checking the structure that a value has. The role of the interface in TS is to name these types and define contracts for your code or third-party code.

Let's write an interface:

        We should note that {} after the interface name does not mean that it is an object. We can understand it as a code block, so do not end it with a comma, but end it with a semicolon.

// interface表示接口,Box表示接口的名字  {}非表示对象,可以理解为代码块
interface Box{
    width:string;
    color:string;
    opacity:number;
}
// 我们可以假设Box就是一种类型 b1就是Box类型
// 我们判断两个对象是否为同一种对象,属性(字段)是否一样,字段类型(字段保存的数据)是否一样

/* 在面向对象的程序中 对象是否有各种各样的[形状]
通过对象的成员和成员的数据类型 可以约束对象的形状 */
let b1:Box;
b1={width:"200px",color:"red",opacity:0.6};
b1={width:"300px",color:"pink",opacity:0.7};

Let’s write another one:

interface Component{
    methods:object;
    watch:object;
    name:string;
}
let c1:Component;
// c1的类型为接口(Component) 则c1为一个对象
// 并且对象的成员必须有methods watch name 并且它们的类型分别为object object string类型
c1={methods:{},watch:{},name:""};

We must note that even if c1 is changed, the type and member name of the object member cannot be changed.

 Also note that the number of object members in the object must correspond one-to-one with the number in the interface. For example, we delete name or add one more member to see what happens.

2. Optional attributes

        So how do we realize, one less member is still established, there is a concept of optional attributes-the attributes in the interface are not all necessary. Some exist only under certain conditions, or may not exist at all.

// 可选属性
interface Box{
    a:number;//必选属性
    b?:string;//可选属性,对象有没有这个属性都可以
}

let b1:Box;
b1={a:100};
b1={a:100,b:"hello"};

But if our object has this optional attribute in its members, then the members of this object must follow the provisions of the interface:

interface Box{
    a:number;//必选属性
    b?:string;//可选属性,对象有没有这个属性都可以
}

let b1:Box;
b1={a:100};//可选属性可以没有
b1.b="66666";//可以添加属性 添加的为可选属性
console.log(b1);//{ a: 100, b: '66666' }

3. Read-only attributes

        Some object properties can only modify their values ​​when the object is just created. You can specify read-only properties by using readonly before the property name:

// 只读属性
interface Box{
    a:number;//必选属性
    b?:string;//可选属性,对象有没有这个属性都可以
    readonly c:boolean;//必选只读属性
} 
let b1:Box;
b1={a:100,c:false};//可选属性可以没有 只读属性不能没有
// 取值
let a=b1.a;
console.log(a);//100
// 存值
b1.a=1111;
console.log(b1);//{ a: 1111, c: false }
// 取值
let c=b1.c;
console.log(c);false
// 存值
b1.c=true;//报错  只读属性不能存值

4. How to write optional read-only attributes

    readonly d?:[number,any]//只读的可选属性,而且是一个元组类型

5. Type description of the object’s attribute name

        In an object, the standard attribute name is a string, and the attribute name of an array-like array is a number (the difference between a true array and an array-like array is that a true array is created by Array, and an array-like array is created by Object)

//  对对象名的属性名的类型描述
interface Person{
    // pro表示属性名 可随便写
    [pro:string]:any;
}
let per1:Person;
per1={"age":100,name:"karen"};
per1={son:{name:"jack"}};
interface myArray{
    [pro:number]:any;//对象属性名是数字 值是any
}

let a1:myArray;
a1=[10,20,30];
a1={0:90,1:100,2:200};

2. Function interface

a.Function

1. The syntax of functions in ts (defining types for functions)

        Each parameter in the parameter list requires a name and type. We can add a type to each parameter and then add a return type to the function itself. TypeScript is able to automatically infer the return value type based on the return statement, so we usually omit it.


function fn (x:number,y:string):number{
	return x*2;
}
let re=fn(100,"hello");
console.log(re);

let re2=fn(100); 
//参数个数少了 编译报错------应有 2 个参数,但获得 1 个。

let re3=fn("hello","hello");
//实参不满足形参类型 编译报错---类型“string”的参数不能赋给类型“number”的参数。

let res4=fn(100,"hello",200);
 //参数个数多了 编译报错----应有 2 个参数,但获得 3 个。

2. Optional parameters

        The number of parameters passed to a function must be consistent with the number of parameters expected by the function. However, in TypeScript we can use ? next to the parameter name to implement the function of optional parameters. There is no doubt that optional parameters must follow required parameters

        Optional parameters, you don’t need to pass actual parameters when passing them to formal parameters, but if you want to pass them, they must conform to the specified type.

3.Default parameters 

        Parameters with default values ​​after all required parameters are optional. Like optional parameters, they can be omitted when calling a function.

//默认参数值(默认参数自动就是可选参数 因此默认参数不用写?来描述)
function fn (x:number,y:string="hello"):number{
	console.log(x,y);
    //fn(100,"test");-------100 test
    // fn(200);-------------200 hello
	return x*2;
}
fn(100,"test");
fn(200);

        Parameters with default values ​​do not need to be placed after the required parameters. If a parameter with a default value appears before a required parameter, the user must explicitly pass in the undefined value to obtain the default value.

//注意  可选参数和默认参数不要设计在函数的必选参数前面
function fn (y:string="hello",x:number):number{
	console.log(x,y)//fn(undefined,1000)-----1000 hello
	return x*2
}
fn(undefined,1000)//不建议这样设计

4.Remaining parameters 

5. Variables of function type

        The way to specify type constraints for a function is through parameters (types) and return values.

let f1:(x:number,y:string)=>number;//描述函数类型的一种表达式 函数的类型
//返回值必须是number 形参必须是number和string
f1=function(a:number,b:string):number{
	let c=a+b
	return 200
}
f1=function(a:number,b:string):number{
	let c=a*3
	return 300
}

    The two ways of writing f1 shown in the figure below only modify the logic. We can say that these two functions are the same function. The parameters satisfy the description, (x:number, y:string) and the return value also satisfies number.

expansion:

interface Box{
	color:string
	length?:number
}
let f2:(x:[number],y:Array<Box>)=>[number,Box[]];
// 中文描述:  
//f2变量是一个函数   
//函数有各种各样(如何区别函数:参数和返回值)


/* f2是一个什么样的函数? 
有两个参数 第一个参数是一个元祖(一个元素而且是number)  第二参数是数组(元素是Box类型)
有一个返回值  类型是元祖(一个是number,一个是数组(Box)) */
f2=function (a:[number],b:Box[]):[number,Box[]] {	
	return [100,[{color:"red"}]]
}

 Note: The formal parameter type cannot be omitted, and the function return value can be omitted.

 b.Function interface

        Function interface is equivalent to defining a name for that type of function. The difference from function type variables is the symbol in front of the return value type"=>"":" and

// 函数类型的变量
let b:number;

let c:(a:string)=>number;
// 赋值c一个函数 要求参数为string类型   函数返回值为number类型
c=(x:string):number=>{return 100}

// 函数类型的接口
interface querySeclector{
	(x:number):string;
    // 表示参数为number类型 返回值为string类型
}
let a:querySeclector;
a=function (x:number):string{
	return x+"hello"
}

Extension: 

 Enhanced Edition:

 Final version:

Guess you like

Origin blog.csdn.net/m0_48465196/article/details/128474441