我不明白为什么这不起作用。我希望 $ObjMap 要求对象返回值,或返回该值的函数。请参阅代码中的注释。任何人都知道如何使这项工作?
type TObj = {|
a: number,
b: string,
c: boolean,
|};
type Extract = <V>(V) => (() => V) | V
type TType = $ObjMap<TObj, Extract>
function a (): string {
return 'a';
}
// Expect a to have an error as it is a function that returns a string.
// $ObjMap states that it must be either a number, or a function that returns
// a number.
const t: TType = {
a,
b: 'v',
c: true,
};
https://flow.org/try/#0C4TwDgpgBAKg8gIwFZQLxQN4B8BQUoCGAXFAHYCuAtghAE4A0eUCJAzsLQJakDmj+AYxIIA9iIA2EAqUZYAvgG4cOUJCgBRAB4cCA4GigAeAGoA+ABTGAlGlNRz5m6jvWoWKMeWroMGOGjoACSISACyBGCG8Mj0Gtq0usCmygBm5KR6nCKkhPZWbBzcPJhMtBDA5LQ5AOQE1UpyygLZ7FDAJL7+BhhMxIT8zCTVAG7VA0JttOQQjIpAA
最佳答案
在我看来,这似乎是实现中的一个限制/错误。原因如下:
如果我们更改 Extract
这样它只会期望原语,我们通过观察一切都按预期工作来建立基线。
type Extract = <V>(V) => V
19: a: a,
^ Cannot assign object literal to `t` because function [1] is incompatible with number [2] in property `a`. [incompatible-type]
References:
11: function a (): string {
^ [1]
2: a: number,
^ [2]
接下来我们修改Extract
只接受返回类型为数字或相应预期值的函数。type Extract = <V>(V) => ((() => number) | V)
现在我们观察到您的预期行为,a
上的错误19: a: a,
^ Cannot assign object literal to `t` because string [1] is incompatible with number [2] in the return value of property `a`. [incompatible-type]
References:
11: function a (): string {
^ [1]
7: type Extract = <V>(V) => ((() => number) | V)
^ [2]
但是,如果我们将接受的类型从 number
更改为至string
错误消失了,这意味着到目前为止一切正常。最后当我们替换
number
与 V
错误消失。这让我觉得解释器有问题解决并回退到 any
作为默认值。我希望静态分析会出现这样的问题,它被称为静态是有原因的。
免责声明:我上面所说的一切都只是想法和假设,我发帖是为了提供帮助,可能完全是垃圾,在这种情况下,我深表歉意。
关于javascript - ObjMap 返回值或函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64509739/