【问题标题】:Flowtype Javascript Inference Not Working as ExpectedFlowtype Javascript 推理未按预期工作
【发布时间】:2016-09-08 02:06:41
【问题描述】:

如果没有注释掉 Reference #2,我无法弄清楚为什么 Flow 无法从 Reference #1 映射函数正确推断返回类型。

如果引用 #2 被注释掉,或者如果我明确地将 Mappable<B> 表示为引用 #1 的返回类型,那么一切都很好。

const map = <A, B>(transform: Transform<A, B>, mappable: Mappable<A>): Mappable<B> => mappable.map(transform);

很想知道为什么会这样!谢谢!

// Types
type Transform<A, B> = (value: A) => B;

// Classes
class Mappable<A> {
  __value: A;
  constructor(value: A) {
    this.__value = value;
  }
  map<B>(transform: Transform<A, B>): Mappable<B> {
    return new Mappable(transform(this.__value));
  }
}

class Container<A> extends Mappable<A> {}

// Transformations
const stringToBase10Number = (value: string): number => parseInt(value, 10);
const numberToString = (value: number): string => value.toString();

// Map Utility (Reference #1)
const map = <A, B>(transform: Transform<A, B>, mappable: Mappable<A>) => mappable.map(transform);

// Log Utility
const log = <T>(value: T): T => { console.log(value); return value; }

// Test Case
const fooContainer = new Container('10');

const fooNumberContainer = map(stringToBase10Number, fooContainer);
map(log, fooNumberContainer); // Logs '1' to the console

// Reference #2
const fooStringContainer = map(numberToString, fooNumberContainer);
map(log, fooStringContainer);

错误:

const fooStringContainer = map(numberToString, fooNumberContainer);
                           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ function call
const map = <A, B>(transform: Transform<A, B>, mappable: Mappable<A>) => mappable.map(transform);
                ^ B. This type is incompatible with
const numberToString = (value: number): string => value.toString();
                               ^^^^^^ number

【问题讨论】:

    标签: javascript functional-programming ramda.js flowtype


    【解决方案1】:

    尝试向map 函数添加返回类型。所以改变

    const map = <A, B>(transform: Transform<A, B>, mappable: Mappable<A>) => mappable.map(transform);
    

    const map = <A, B>(transform: Transform<A, B>, mappable: Mappable<A>): Mappable<B> => mappable.map(transform);
    

    Your full example before

    Your full example after

    为什么需要这个返回类型注解?这是因为 Flow 不推断多态类型。如果函数总是返回string,那没关系。但由于返回Mappable&lt;B&gt;,所以需要注解。

    这是另一个解决此问题的答案:Polymorphic Anonymous Functions Type Aliases

    【讨论】:

    • 啊! “流不推断多态类型”
    猜你喜欢
    • 1970-01-01
    • 2020-04-10
    • 2016-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-11
    • 2023-03-20
    • 1970-01-01
    相关资源
    最近更新 更多