代码之家  ›  专栏  ›  技术社区  ›  ABOS

为什么部分接口不接受附加字段?

  •  1
  • ABOS  · 技术社区  · 7 年前
    interface User {
      name: string;
      age: number;  
    }
    
    let user: Partial<User> = {name: 'John', address: '123 Main st.'}
    

    所以typescript会抱怨 address 接口中不存在 User 我的理解是只要 Partial<User> 是右侧对象的子集,它应该是有效的强制。如何正确理解它?

    2 回复  |  直到 7 年前
        1
  •  2
  •   Community Mohan Dere    6 年前

    它叫 超额财产检查

    来自typescript文档( https://www.typescriptlang.org/docs/handbook/interfaces.html#excess-property-checks ):

    ... TypeScript的立场是,此代码中可能存在错误。对象文字得到特殊处理,并在将其分配给其他变量或作为参数传递时进行多余的属性检查。如果对象文字具有目标类型没有的任何属性,您将得到一个错误。

        2
  •  1
  •   inoabrian    7 年前

    @阿布斯

    Partial<User> 为您做的是使用户界面的属性成为可选的。

    与此类似,,

    interface User {
       name?: string;
       age?: number;
    }
    

    我想你真正想做的是进一步扩展你的用户界面,

    interface User {
        name: string;
        age: number;
    }
    
    
    interface Mod extends User {
        address: string;
    }
    
    // this here then makes age from the user interface optional but also allows 
    // you to now have the address property.
    
    let user: Partial<Mod> = {name: "John", address: "123 Main st."};
    

    class Users implements Mod {
        address: string;
        name: string;
        age: number;
    
        // we can make the address and age defaulted values if not provided
        constructor(name: string, address: string = "", age: number = 0) {
            this.name = name;
            this.address = address;
            this.age = age;
        }
    }
    
    let user: Mod = new Users("John");
    
    console.log(user.name);     // "John"
    console.log(user.address);  // ""
    console.log(user.age);      // 0
    
    推荐文章