Deep understanding of TypeScript - interface

1, limited attributes

object qualification

This input must only have a name attribute of type string, otherwise an error will be reported.

/*对象限制*/
function sayName1(obj: {
     
      name: string }) {
    
    
	console.log("我的名字叫:" + obj.name);
}
sayName1({
    
    name: "张三"})

Effect:

我的名字叫:张三

Interface restrictions

The function is the same as above.

interface People {
    
    
	name: string
}
function sayName2(obj: People) {
    
    
	console.log("我的名字叫:" + obj.name);
}
sayName2({
    
    name: "李四"})

Effect:

我的名字叫:李四

some spelling

Optional
None.

As a type, there will be code hints.

interface People {
    
    
	name: string
	age?:number
}

read-only
This is the general qualification of the property

interface People {
    
    
	readonly id:number
	name: string
	age?:number
}

3, limited to other

function type

You can limit the return of the function.

The parameter name is not required, but the type needs to be consistent.

interface sayName {
    
    
	(obj: {
    
     name: string }): void
}
let a: sayName
a = function (s: {
     
      name: string }): void {
    
    
	console.log(s.name)
}

array type

The value type of an array can be qualified.

interface MyStringArray {
    
    
	[index: number]: string;
}

let myArray: MyStringArray;
myArray = ["AAA", "BBB"];

let myStr: string = myArray[0];

4, limited class

Simple to use

A class implements an interface and must have all its properties and methods.

interface User {
    
    
	name:string
	sayName():void
}
class MyUser implements User {
    
    
	name:string;
	sayName() {
    
    
		console.log(this.name)
	}
}
let a=new MyUser()
a.name="( ⊙ o ⊙ )啊!"
a.sayName()

inheritance relationship

An interface can inherit from multiple interfaces. Limits will be superimposed.

Interfaces can also inherit from classes.

5, fool the compiler (not recommended)

Tell the compiler that this object belongs to this interface and doesn't need to be checked.

type assertion

After an assertion, the compiler doesn't check for it.

interface People {
    
    
	name: string
}
function sayName2(obj: People) {
    
    
	console.log(1)
}
sayName2({
    
    } as People)

attribute qualification

Relax the attribute requirements, and the compiler will not report an error.

interface People {
    
    
	name?: string
	[propName: string]: any
}
function sayName2(obj: People) {
    
    
	console.log(1)
}
sayName2({
    
    age:3})

Guess you like

Origin blog.csdn.net/qq_37284843/article/details/123768071