TS学习
Interface(接口)
基本使用
interface LabelValue{
label:string;
}
function printLabel(labelObj:LabelValue){
console.log(labelObj.label)
}
let myObj = {label:"hello"};
printLabel(myObj)
可选属性
interface USB{
name:string;
age?:number;
}
function printUSB(pu:USB){
if(pu.age){
console.log(pu.name +":" +pu.age)
}else{
console.log(pu.name)
}
}
let my={name:"ime"}
let my1 ={name:"liao",age:18}
printUSB(my1)
函数类型
interface SearchFunc{
(source:string,subString:string):boolean;
}
let mySearch:SearchFunc;
mySearch = function(str:string,sub:string){
let result = str.search(sub)
if(result != -1){
return true
}else{
return false
}
}
let r = mySearch("string","str")
console.log(r) //true
接口的数组类型
interface StringArray{
[index:number]:string
}
let myArr:StringArray;
myArr =["a","b"];
alert(myArr[0]);
class实现接口
interface ColockInterface{
currentTime:Date;
setTime(d:Date);
}
class Clock implements ColockInterface{
currentTime:Date;
setTime(d:Date){
this.currentTime = d
}
constructor(h:number,m:number){
}
}
接口类型与混合类型
interface Shape{
color:string
}
interface PenStroke{
penWidth:number
}
interface Square extends Shape,PenStroke{
sideLength:number
}
let s = <Square>{};
s.color = "bule"
s.penWidth = 10
s.sideLength =10
混合接口
interface Counter{
interval:number;
reset():void;
(start:number):string
}
let c:Counter;
c(10)
c.reset()