美文网首页
TypeScript学习之——接口(个人笔记)

TypeScript学习之——接口(个人笔记)

作者: kevision | 来源:发表于2022-11-18 19:39 被阅读0次

    介绍


    接口:约定一个对象中有哪些成员,并且约定成员的类型。作用是对数据进行类型约束,在实际运行的阶段并没有意义。编译后接口会移除。

    基本用法


    interface Post { // 定义一个接口Post,约定对象中有title和content成员
        title: string
        content: string
    }
    function printPost(post: Post) {
        console.log(post.title)
        console.log(post.content)
    }
    
    printPost({ // 多传和少传都会提示错误
        title: 'my title',
        content: 'my content'
    })
    

    可选成员、只读成员和动态成员


    // 可选成员和动态成员不能同时定义到一个接口里面
    interface MyCache {
        title: string
        content: string
        subtitle?: string // 可选成员:后面加?
        readonly summary: string // 只读成员:前面加readonly
    }
    const cache: MyCache = {
        title: 'my title',
        content: 'my content',
        summary: '摘要'
    }
    // cache.summary = 'xxx' 只读属性不可以修改
    
    interface More {
        [prop: string]: string | number // 动态成员:[]表示动态成员,prop不是固定的,可以定义其它的名字
    }
    const more: More = {
        name: 'jack',
        age: 18
    }
    

    相关文章

      网友评论

          本文标题:TypeScript学习之——接口(个人笔记)

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