美文网首页
ts接口 interface

ts接口 interface

作者: nora_wang | 来源:发表于2020-05-10 23:07 被阅读0次

概念:可以用来约束一个函数,对象,以及类的结构和类型

1.对象类型的接口

//定义接口
interface ListItem{
    id:number;
    name:string
}
interface List {
    data:ListItem[]
}
function getListId(list:List) {
    list.data.forEach(item=>{
        console.log(item.id,item.name)
    })
}

//允许传入的list有除了接口定义的其他值,但接口中规定的值必须要有
let list = {
    data:[
        {id:1,name:'hemff',age:13}
    ]
}
/*若直接传人对象内容(对象字面量),ts会对其余的值进行类型检查,解决方法1:将内容赋值给一个变量  2.添加类型断言 as+对象类型 3.给接口添加[x:string]:any  */
getListId({
    data:[
        {id:1,name:'hemff',age:13}
    ]
} as List)

2.函数类型的接口

//函数类型的接口 (两种定义方式)
// 第一种
interface Add{
    (x:number,y:number):number
}
// 第二种
// type Add = (x:number,y:number) => number

let add:Add = (a,b)=> { return a+b }

console.log(add(1,2)) //3

3.混合类型的接口(一个接口既可以定义一个函数,也可以定义一个对象)

//混合类型接口
interface MixItf {
    ():void;
    msg:string;
    dosomething():void
}
function getMix(){
    let lib:MixItf = (() => {}) as MixItf;
    lib.msg = 'rose';
    lib.dosomething = () => {}
    return lib;
}
let getMix1 = getMix()
console.log(getMix1.msg) //rose

相关文章

  • ts接口 interface

    概念:可以用来约束一个函数,对象,以及类的结构和类型 1.对象类型的接口 2.函数类型的接口 3.混合类型的接口(...

  • TypeScript基础知识

    命令 查看版本:tsc -v 运行ts文件:tsc xx.ts 数据类型 接口Interface 类和接口 泛型基...

  • angular中的核心概念

    组件 指令 服务 依赖注入 模块 ts中interface与class的区别 interface -- 接口只声明...

  • typeScript语法

    ts类型 ts联合类型使用或 ts定义任意类型any ts定义函数返回值的类型 ts中的类定义 interface接口

  • TS typescript 接口 interface

    接口之间叫继承(extends) 类和接口之间叫实现(implements) 基础定义接口 常用接口定义方法 类的类型

  • typescript中type和interface区别

    在ts中,定义类型由两种方式:接口(interface)和类型别名(type alias)interface只能定...

  • extends与implements区别及使用

    这是实例化对象的两种写法 1.TS中interface与class区别 interface:接口之声明成员方法,不...

  • TypeScript学习(一)- Class

    在最近看一些代码时,发现ts的class可以当做接口(interface)用。为了知道ts的class还有哪些骚操...

  • typescript修炼指南(二)

    大纲 本章主要讲解一些ts的常规用法,涉及以下内容: interface: 接口 class : 类 functi...

  • 接口

    interface 接口 implements 类实现接口 public interface 接口名{ 接口的成员...

网友评论

      本文标题:ts接口 interface

      本文链接:https://www.haomeiwen.com/subject/vopsnhtx.html