【问题标题】:Flow Generic Function to create Generic Type流泛型函数以创建泛型类型
【发布时间】:2018-04-14 01:40:55
【问题描述】:

假设我有这个通用流类型:

/* @flow */

type Cat<T> = {
  get:()=>T
};

我想创建一个创建猫的函数:

const makeCat:<U>(getter:()=>U)=>Cat<U> 
             = (getter) => ({get:getter});

Flow 给我以下错误:

Cannot assign function to `makeCat` because `U` [1] is incompatible with `U` [2] in the return value of property `get` of the return value.

我尝试了几种不同的方法来定义传入的“getter”的类型,但总是同样的错误。

【问题讨论】:

标签: javascript flowtype


【解决方案1】:

试试这个。我将它的逻辑分解为几个额外的步骤,以使其更易于理解。该解决方案的关键部分是使用* 告诉流程在使用makeCat 函数时“填空”。

type Cat<T> = {
  get: () => T
}

// define signature of "makeCat" function
type MakeCat<U> = (getter: () => U) => Cat<U>

// use * to infer the variable at usage
const makeCat: MakeCat<*> = getter => ({ get: getter })

// inferred as Cat<string>
const cat = makeCat(() => 'secret')

// inferred as string
const value = cat.get()

【讨论】:

    【解决方案2】:

    基于@kindaro 的回答,但简化为不必定义中间函数类型,只需使用常规的“老式”函数声明形式:

    type Cat<T> = { get: () => T };
    
    function makeCat<U>(getter: () => U): Cat<U> {
      return { get: getter };
    }
    
    // inferred as Cat<string>
    const cat: Cat<string> = makeCat(() => 'secret');
    // const cat: Cat<number> = makeCat(() => 'secret');  // Yields error
    
    // inferred as string
    const value: string = cat.get();
    // const value: number = cat.get();  // Yields error
    

    Flow Try link here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多