ts中定义接口(Interface)0基础教学

接口

1.定义接口

接口定义只能定义类型,不能直接赋值,要通过类似于类的实例化的方式,给其赋值。

interface Person {
  name: string;
  age: number;
}
let p1: Person = {
  name: "剑非出我心",
  age: 18,
};
console.log(p1);

2.接口中的属性

       1.可选属性

       name后面+?变成可选属性

      2.只读属性 在name (属性)前面添加readonly 不能修改

      3.使用接口定义函数数据类型

interface fn {
  (m: string): void;
}
let f1: fn = function (m): void {
  console.log("2222", m);
};
f1("100");

interface fn1{
    (m:string,n:number):string
}
let f2:fn1 = (m,n)=>{
return `${m}永远${n}`
}
console.log(f2("剑非出我心",18))

4.接口中使用函数

interface newArr{
    [name:number]:string
}
interface Say{
    ():string
}
interface women{
    name:string,
    age:number,
    say:Say,
    like:newArr
}
let liugege:women={
    name:"剑非出我心",
    age:18,
    say():string{
        return `${this.name}早上说:“hello world”`
    },
    like:["写博客","学前端"]
}
console.log(liugege)
console.log(liugege.say())

5. 使用接口定义数组数据类型

统称为可索引接口 name是固定写法

1)数组类型

interface newArr{
    [name:number]:string
}
let arr1 = ["刘","管","张"]
console.log(arr1[1])

 

2)对象类型

interface newObj{
    [name:string]:string
}
let obj = {
    name:"貂蝉",
    age:30
}
console.log(obj["name"]) 

接口的继承

interface me{
    name:string,
    age:number,
    say():string
}

interface honey extends me{
    love:Array<string>
    play():any
}
let Liu:honey={
    love:['打篮球','写ts'],
    play(){
        return `夜晚微醺`
    },
    name:"剑非出我心",
    age:20,
    say(){
        return `${this.name}喜欢${this.love[0]}并且对它说 hello world`
    }
}
console.log(Liu.say())

 

下篇文章将讲解类的属性,以及怎样用类去实现接口

 

 

 

 

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

剑非出我心

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值