前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >typescript 入门-接口

typescript 入门-接口

作者头像
copy_left
发布2021-06-11 18:13:16
2430
发布2021-06-11 18:13:16
举报
文章被收录于专栏:方球方球

interface 定义

代码语言:javascript
复制
interface i_Tree{
  leftLeaf: string
  rightLeaf: string
}
// 作为类型定义
const tree: i_Tree = {
  leftLeaf: 'left',
  rightLeaf: 'right'
}

可选属性

代码语言:javascript
复制
interface Man{
   name: string // 必选
   job?: string // 可选
}

只读

代码语言:javascript
复制
interface Man{
  readonly sex:string
  name: string
  job?: string
}

函数描述

代码语言:javascript
复制
interface i_talk{
  (msg:string): void;
}
const talk:i_talk = (msg: string) => {
  console.log(msg)
}

可索引

代码语言:javascript
复制
interface i_list{
  [index: number]: string
}
const li: i_list = ['ni', 'mi']

类描述

代码语言:javascript
复制
interface i_Man{
  name: string
}


class Man implements i_Man{
  name:string
  constructor(name: string) {
    this.name = name
  }
}




const c = new Man('cc')
console.log(c.name)

类构造器描述

代码语言:javascript
复制
interface i_Man{
  name: string
}


class Man implements i_Man{
  name:string
  constructor(name: string) {
    this.name = name
  }
}


// 定义构造函数接口
interface i_ManConstructor{
  new (name:string): i_Man
}


// 接收类定义作为参数
function createMan(c: i_ManConstructor, name: string):i_Man{
  return new c(name)
}

混合类型

代码语言:javascript
复制
interface i_talk{
  (msg?: string): void
  defaultMsg?: string
}




const talk: i_talk = function (msg?: string): void{
  console.log(msg || talk.defaultMsg)
}




talk.defaultMsg = 'not find msg'
talk()
// 函数也是对象,可以拥有自己的属性

继承接口

代码语言:javascript
复制
interface i_A{
  propA: string
}


interface i_B{
  propB: string
}


interface i_C extends i_A, i_B{
  propC: string
}


const c: i_C = {
  propA: 'a',
  propB: 'b',
  propC: 'c',
} 

继承类

代码语言:javascript
复制
class Control {
    private state: any;
}


interface SelectableControl extends Control {
    select(): void;
}


class Button extends Control implements SelectableControl {
    select() { }
}


class TextBox extends Control {
    select() { }
}


// 错误:“Image”类型缺少“state”属性。
class Image implements SelectableControl {
    select() { }
}


class Location {}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • interface 定义
  • 可选属性
  • 只读
  • 函数描述
  • 可索引
  • 类描述
  • 类构造器描述
  • 混合类型
  • 继承接口
  • 继承类
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档