gpt4 book ai didi

javascript - 流、对象字面量与联合不兼容

转载 作者:行者123 更新时间:2023-12-03 03:25:01 31 4
gpt4 key购买 nike

如果我有一个函数返回一个包含数据库信息的对象或一个空对象,如下所示:

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

}

我收到很多 Flow 错误,例如:

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 = {||};

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

最佳答案

可能的补丁包括密封/卡住空的Object文字。但这只会绕过根本问题:您已经定义了一个精确的 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

您可以看到,只有空对象字面量才是流中未密封的Object类型。此时不需要精确的 Object 类型,您可以安全地从 {||} 中删除精确的类型注释。那么它们有什么用呢?

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

使用精确的Object类型,您可以更好地控制宽度子类型。

但是,宽度子类型也有其自身的陷阱,因为它会删除类型信息,正如您通过失败的属性访问 o.foo 所看到的那样。

关于javascript - 流、对象字面量与联合不兼容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46371119/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com