接口
Interface
接口的作用类似于抽象类,不同点在于接口中的所有方法和属性都是没有实值的,换句话说接口中的所有方法都是抽象方法。接口主要负责定义一个类的结构,接口可以去限制一个对象的接口,对象只有包含接口中定义的所有属性和方法时才能匹配接口。同时,可以让一个类去实现接口,实现接口时类中要保护接口中的所有属性。我们来看下面这个例子:
TypeScript
interface Person{
name: string;
sayHello():void;
}
function fn(per: Person){
per.sayHello();
}
fn({name:'孙悟空', sayHello() {console.log(`Hello, 我是 ${this.name}`)}});
这里注意接口中只有我们的对象方法,没有具体的实现,实现都是在类中使用implements
来实现的,我们看下面例子:
TypeScript
// 接口中所有的方法都是抽象方法
interface myInter{
name: string;
sayHello(): void;
}
class MyClass implements myInter{
name: string;
constructor(name: string) {
this.name = name;
}
sayHello(): void {
console.log('hello');
}
}
泛型(Generic)
定义一个函数或类时,有些情况下无法确定其中要使用的具体类型(返回值、参数、属性的类型不能确定),此时泛型便能够发挥作用。我们看下面例子:
TypeScript
function test(arg: any): any{
return arg;
}
假如我们使用上面例子中的方式,能确定的入参和出参都是任意的,并不能保证是同一种数据类型,所以我们就可以使用泛型,再看一个例子:
TypeScript
function test<T>(arg: T): T{
return arg;
}
上面内容,是可以保证我们的入参和出参都是一致的数据类型,这里的<T>
就是指泛型。 使用上面泛型有两种方式
1.直接使用
TypeScript
test(10)
2.指定类型
TypeScript
test<number>(10)
也可以时指定多个类型
TypeScript
function test<T, K>(a: T, b: K): K{
return b;
}
test<number, string>(10, "hello");
这里说一个小技巧:使用泛型时,完全可以将泛型当成是一个普通的类去使用
类中同样可以使用泛型
TypeScript
class MyClass<T>{
prop: T;
constructor(prop: T){
this.prop = prop;
}
}
也可以对泛型的类型进行约束
TypeScript
interface MyInter{
length: number;
}
function test<T extends MyInter>(arg: T): number{
return arg.length;
}
index.less
less
@bg-color:#b7d4a8;
*{
padding: 0;
margin: 0;
box-sizing: border-box;
}
body{
font:bold 20px "Courier";
overflow: hidden;
}
// 设置主窗口的样式
#main{
width: 360px;
height: 420px;
background-color: @bg-color;
margin: 100px auto;
border: 10px solid black;
border-radius: 40px;
display: flex;
flex-flow: column; // 默认是row方向排列,这里改成column 方向
align-items: center;
justify-content: space-around;
#stage{
width: 304px;
height: 304px;
border:2px solid black;
position: relative;
#sink{
&>div{
width: 10px;
height: 10px;
background-color: black;
border: 1px solid @bg-color;
position: absolute;
}
}
#food{
width: 10px;
height: 10px;
position: absolute;
left: 40px;
top: 100px;
// background-color: red;
display: flex;
flex-flow: row wrap;
justify-content: space-between;
align-content: space-between;
&>div{
width: 4px;
height: 4px;
background-color:black;
transform:rotate(45deg);
}
}
}
#score-panel{
width: 300px;
display: flex;
justify-content: space-between;
}
}
使用T extends MyInter表示泛型T必须是MyInter的子类,不一定非要使用接口类和抽象类同样适用。
感谢大家观看,我们下次见