// 接口 自定义的静态类型
// 只能是对象或者函数
// 1 定义接口
interface person {
// readonly key 作用:设置某个属性为只读类型, 只要修改key就会报错
readonly name: string,
// key? 作用:设置某个属性可有可无
age?: number,
// propName 作用 传入不确定的属性
[propName: string]: any,
// say函数,返回值为string
say(): string
}
// 使用接口
function getPerson(person: person): string { // 表示person 中必须有name 为 string
console.log(person.name)
// person.name = 'asdfasdf'; // 报错
return person.name
}
getPerson({
name: 'aa',
aa: 123,
say() {
return ''
}
})
// 2 在类中使用接口
// implements interfaceName 在类使用接口
// 注意: 类中必须具备接口中属性。
class user implements person {
cname = 'aa';
name = '123';
// say = 123
say() {
return 'aaa'
}
}
// 3接口继承 extends
interface zy {
name: string
age?: number
}
// blc继承了 zy
interface blc extends zy {
dec: string
}
// obj 赋值时,也需要加入zy接口中属性
let obj: blc = {
dec: 'woshi dfds',
name: '',
age: 34
}
// 4 接口为函数时候
// sayHollow 是函数
interface sayHollow {
// 形参为 string类型 返回值为字符串类型
(word: string): string
}
// let say:sayHollow = {} // bug
// 要求 say变量赋值为 函数 并且返回值为字符串;执行时候,实参为字符串
let say:sayHollow = function(a){
console.log(a);
return ''
}
// say(123) // bug 123类型不对
say('123')
// let foo:(a:string)=>string = (a)=>{
// return ''
// }
// let foo1:(b:number,a:string)=>string = function(b,a){
// return '123'
// }
// foo1(1,'12')
interface a {
(zidingyi:string):string
}
let foo:a = (a)=>{
return ''
}
interface b{
(b:number,a:string):string
}
let foo1:b = function(b,a){
return '123'
}
foo1(1,'12')