接口
接口的关键字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'))
复制代码
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END