码迷,mamicode.com
首页 > 其他好文 > 详细

TypeScript 中的interface接口

时间:2021-01-11 11:28:12      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:get   return   int   href   定义   约束   number   tps   blank   

使用接口约束类型

interface Girl {
  name: string;
  age: number;
  bust: number;
}

const screenResume = (girl: Girl) => {
  girl.age < 24 && girl.bust >= 90 && console.log(girl.name + "进入面试");
  girl.age > 24 || (girl.bust < 90 && console.log(girl.name + "你被淘汰"));
};

const getResume = (girl: Girl) => {
  console.log(girl.name + "年龄是:" + girl.age);
  console.log(girl.name + "胸围是:" + girl.bust);
};
const girl = {
  name: "大脚",
  age: 18,
  bust: 94,
};

screenResume(girl);
getResume(girl);

接口和类型别名很像,但是类型别名可以直接给类型,比如string,而接口必须代表对象。

接口非必选值的定义

// 使用 ? 来标记可选值
interface Girl {
  name: string;
  age: number;
  bust: number;
  waistline?: number;
}
const getResume = (girl: Girl) => {
  console.log(girl.name + "年龄是:" + girl.age);
  console.log(girl.name + "胸围是:" + girl.bust);
  girl.waistline && console.log(girl.name + "腰围是:" + girl.waistline);
};

允许加入任意值

interface Girl {
  name: string;
  age: number;
  bust: number;
  waistline?: number;
  [propname: string]: any;
}
const girl = {
  name: "大脚",
  age: 18,
  bust: 94,
  waistline: 21,
  sex: "女",
};
const getResume = (girl: Girl) => {
  console.log(girl.name + "年龄是:" + girl.age);
  console.log(girl.name + "胸围是:" + girl.bust);
  girl.waistline && console.log(girl.name + "腰围是:" + girl.waistline);
  girl.sex && console.log(girl.name + "性别是:" + girl.sex);
};

接口里的方法

interface Girl {
  name: string;
  age: number;
  bust: number;
  waistline?: number;
  [propname: string]: any;
  say(): string;
}

const girl = {
  name: "大脚",
  age: 18,
  bust: 94,
  waistline: 21,
  sex: "女",
  say() {
    return "欢迎光临 ,红浪漫洗浴!!";
  },
};

接口和类的约束

class XiaoJieJie implements Girl {
  name = "刘英";
  age = 18;
  bust = 90;
  say() {
    return "欢迎光临 ,红浪漫洗浴!!";
  }
}

接口间的继承

interface Teacher extends Girl {
  teach(): string;
}

参考:
技术胖——TypeScript从入门到精通(08. TypeScript中的interface接口)
技术胖——TypeScript从入门到精通(09. TypeScript中的interface接口 2)

TypeScript 中的interface接口

标签:get   return   int   href   定义   约束   number   tps   blank   

原文地址:https://www.cnblogs.com/xch-jiang/p/14254107.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!