美文网首页
学习TypeScript(接口和对象类型)

学习TypeScript(接口和对象类型)

作者: jamesXiao_ | 来源:发表于2023-05-28 14:49 被阅读0次

    interface 与 对象

    在typescript中,我们定义对象的方式要用到关键字 interface(接口),在个人的理解中,使用interface来定义一种约束,使数据结构满足定义的约束

    // 会报错,因为在Person接口定义了a,b2个字段,但是在对象里面缺少b字段
    // 使用接口约束的时候不能多一个字段不能少一个字段
    // 必须和接口一致
    interface Person {
        a:string,
        b:string
    }
    
    const person: Person = {
      a: '123'
    }
    
    // 重名的interface 会产生合并
    interface Person {
      name: string
    }
    
    interface Person {
      age: number
    }
    
    const user: Person = {
      name: 'xhj',
      age: 18
    };
    
    // 接口可以继承
    // 但是不允许有(同名的字段,类型不一样)
    interface Name {
      name: string;
    }
    
    interface Age {
      age: number;
    }
    
    interface Person extends Name, Age {
      sex: string;
    }
    
    const person: Person = {
      name: "xhj",
      age: 18,
      sex: "man",
    };
    

    可选属性 使用?操作符

    // 可选属性的含义是该属性可以不存在
    // 所以说这样写也是没问题的
    interface Person {
        b?:string,
        a:string
    }
     
    const person:Person  = {
        a:"213"
    }
    

    任意属性 [propName: string]

    // 在这个例子当中我们看到接口中并没有定义C但是并没有报错
    // 应为我们定义了[propName: string]: any;
    // 允许添加新的任意属性
    interface Person {
        b?:string,
        a:string,
        [propName: string]: any;
    }
     
    const person:Person  = {
        a:"213",
        c:"123"
    }
    

    只读属性 readonly

    // 这样写是会报错的
    // 应为a是只读的不允许重新赋值
    interface Person {
        b?: string,
        readonly a: string,
        [propName: string]: any;
    }
     
    const person: Person = {
        a: "213",
        c: "123"
    }
     
    person.a = 123
    

    添加函数

    interface Person {
        b?: string,
        readonly a: string,
        [propName: string]: any;
        cb:()=>void
    }
     
    const person: Person = {
        a: "213",
        c: "123",
        cb:()=>{
            console.log(123)
        }
    }
    

    相关文章

      网友评论

          本文标题:学习TypeScript(接口和对象类型)

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