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

流,对象文字与union不兼容

  •  1
  • Newtang  · 技术社区  · 9 年前

    getThingFromDB: async function(id:string):Promise<EventObj|Empty>{
        const fromDB = await dao.getEvent(id);
        if(fromDB && fromDB.length){
            return fromDB[0];
        }
        return {};
    
    }
    

    我得到了很多流错误,比如:

    return {};
           ^^ object literal. This type is incompatible with
    getThingFromDB: async function(id:string):Promise<EventObj|Empty>{                                                                                
                                                      ^^^^^^^^^^^^^^ union: EventObj | Empty
    

    或

    getThingFromDB: async function(id:string):Promise<EventObj|Empty>                                                                                      
                                                      ^^^^^^^^ property `id`. Property not found in
    return {};
           ^^ object literal
    

    declare type EventObj = {
        id:string,
        name:string,
        urlName:string
    };
    
    declare type Empty = {||};
    

    我错过了什么?如何正确地满足这些错误。

    1 回复  |  直到 9 年前
        1
  •  2
  •   user6445533 user6445533    9 年前

    Object 字面意义的但这只是绕过了根本问题:您定义了一个精确的 对象 尽管您只需要一个密封的,但请键入:

    type Empty = {};
    
    let o = {};
    let p = {foo: true};
    let q: Empty = {};
    
    o.foo = true; // type checks
    p.bar = true; // type error
    q.foo = true; // type error
    

    您可以看到,只有空对象文字是未密封的 输入flow。准确的 对象 {||} . 它们有什么用处?

    type Foo = {|foo: boolean|};
    type Bar = {bar: boolean};
    
    const f = (o: Foo) => o;
    const g = (o: Bar) => o;
    
    f({foo: true, bar: true}); // type error
    let o = g({foo: true, bar: true}); // type checks
    
    o.foo; // type error
    

    带精确 对象 类型您可以更好地控制宽度子类型。

    o.foo .