(小白学习之接口篇,请多指教)
ts接口主要用来定义一个对象的类型,通过interface
关键字来定义
举个🌰:
interface Person {
name: string;
age: number
}
const xiong: Person = {
name: '熊',
age: 18
}
属性可选:
有时候我们不确定对象的某个属性是否存在,这时候就需要将该属性设置成可选属性
interface Person {
name: string;
age: number;
money?: number;
}
const xiong: Person = {
name: '熊',
age: 18,
}
const xiongxiong: Person = {
name: '熊',
age: 18,
money:999999
}
只读属性:
字面上的意思,如果某个属性的类型定义为只读,那么改接口的变量不能修改该属性,举个🌰:
interface Person {
name: string;
readonly age: number;
}
const xiong: Person = {
name: '熊',
age: 18,
}
console.log(xiong.age) // 18
xiong.age = 20 //报错
混合类型:
当一个函数既可以直接调用,又拥有一些属性的时候,就需要使用interface定义函数类型
interface Func {
(name: string): string;
age: number;
}
const myFunc = function(name: string) {
return name;
};
myFunc.age = 18;
const func: Func = myFunc;
console.log(func);
类型索引:
当定义数组或者不确定属性的对象时,可以使用类型索引
interface ObjType {
[value: string]: string;
}
const object: ObjType = {
name: "xiong",
like: "bear"
};
console.log(object); //{name: "xiong", like: "bear"}
// 如果索引是number类型 那么该类型也可以作为数组
interface ArrType {
[value: number]: string;
}
const obj: ArrType = {
1: "xiong",
2: "bear"
};
const array: ArrType = ["xiong", "bear"];
console.log(array); // ["xiong", "bear"]
console.log(obj); // {1: "xiong", 2: "bear"}
一旦定义了类型索引,那么再定义具名属性类型必须与索引类型一致
interface AnyObj {
[name: string]: string;
gender: string; //pass
// age: number; // error age的值类型需要时string
}
interface Any {
[name: string]: string | number;
// [name: any]: any; //error 索引签名参数类型必须为'string'或'number'
// 或者可以定义为[name: string]: string | number;
gender: string; //pass
age: number; // error age的值类型需要时string
}
类类型:
interface除了能约束普通变量,也可以约束类,让类按照约定来实现
举个简单🌰:
interface Person {
name: string;
age: number;
}
//通过implements关键字来约束xiong按照Person类型来实现
class xiong implements Person {
name = 'xiong'
age = 18
}
也可以约束类型中的方法,举个🌰:
interface Person {
getMoney(num:number):number
}
class xiong implements Person {
getMoney(num) {
return num*2
}
}
接口继承:
接口和class一样,可以继承
举个简单🌰:
interface Person {
name: string;
age: number;
}
interface Teacher extends Person {
job: string
}
也可以继承多个接口,🌰:
interface Person {
name: string;
age: number;
}
interface Teacher {
book: string;
}
interface Xiong extends Person, Teacher {
job: string;
}
const XiongXiong: Xiong = {
name: "xiongxiong",
age: 18,
job: "it",
book: "qqq"
};
console.log(XiongXiong); //{name: "xiongxiong", age: 18, job: "it", book: "qqq"}
一个接口也可以继承一个class ,🌰:
class Action {
run = true;
}
interface Movement extends Action {
sit: boolean;
}
const man: Movement = {
run: true,
sit: true
};
console.log(man);
网友评论