接口
接口的关键字interface
interface IStudent {
name: string
no: number
}
function say(stu: IStudent) {
console.log(stu)
}
say({ name: 'hhh', no: 1 })
可选属性
interface IStudent {
name: string
no: number
tag?: string //可选属性
}
function say(stu: IStudent) {
console.log(stu)
}
say({ name: 'hhh', no: 1 })
say({ name: 'haha', no: 2, tag: '三好学生' })
只读属性 ,关键字 readonly
interface IStudent {
readonly firtName: string
name: string
no: number
tag?: string
}
function say(stu: IStudent) {
console.log(stu)
}
let stu1: IStudent = { name: '张三', no: 1, firtName: '张' }
let stu2: IStudent = { name: '李四', no: 2, tag: '三好学生', firtName: '李' }
// stu1.firtName = '王'
console.log(stu1.firtName)
say(stu1)
say(stu2)
用接口声明函数
interface ISay1 {
(name: string): string
}
let say1: ISay1 = (str1: string) => { return str1 }
let say2: ISay1 = (str1: string) => { return str1 }
// function say1(st1: string): string {
// return st1
// }
console.log(say1('say1'), say2('say2'))
可索引类型的接口
声明的数组
interface StringArray {
[index: number]: string;
}
let myArray: StringArray;
myArray = ["Bob", "Fred"];
声明的map
interface IMap {
[key: string]: string;
}
let m: IMap = { "a": "a" }
console.log(m)
类类型,接口对class的约束
// 接口重在约束
interface ILee {
firstname: string
}
class Lee implements ILee {
firstname: string
}
let lee = new Lee()
lee.firstname = 'Lee'
console.log(lee)
接口的继承
interface IAnimal {
name: string
}
interface ICat extends IAnimal {
say(str: string): string
}
interface IDog extends IAnimal {
say(str: string, s2: string): string
}
class Cat implements ICat {
name: string
say(s1: string): string {
return s1
}
}
// 接口重在签名,也就是约束
class Dog implements IDog {
name: string
say(s1: string, st2: string): string {
return s1 + st2
}
}
let cat: ICat = new Cat()
console.log(cat.say('cat'))
let dog: IDog = new Dog()
console.log(dog.say('dog1', 'dog2'))
常见问题FAQ
- 免费下载或者VIP会员专享资源能否直接商用?
- 本站所有资源版权均属于原作者所有,这里所提供资源均只能用于参考学习用,请勿直接商用。若由于商用引起版权纠纷,一切责任均由使用者承担。更多说明请参考 VIP介绍。
- 提示下载完但解压或打开不了?
- 找不到素材资源介绍文章里的示例图片?
- 模板不会安装或需要功能定制以及二次开发?
发表评论
还没有评论,快来抢沙发吧!