flow javascript泛型类型“无法从值位置引用类型`CustomType` [1]。”

问题描述 投票:0回答:1

我试图调用异步函数并指定自定义类型(让我们称之为“CustomType”)。我已经在该类型中指定了一些随机属性,只是要理解它是来自数据库的内容(内容可能因检索项目而异,我对存储在NoSql中的每种文件都有许多不同的“CustomType”)数据库)。

这是使用https://flow.org/try可测试的代码

/* @flow */

// Type that would be returned in the case of usage of "mySpecificCallFunc(): Promise<Array<CustomType>>" defined below
declare type CustomType = { 
  prop1: boolean,
  prop2: string,
  prop3: Date
}

// Generic function that does the hard work
async function asyncFunc<T>(dateStart: Date, otherArgument: string):Promise<Array<T>>
{
  let r:Array<T> = [] // do a call that returns an array that must be of a specific type
  return r
}

// High level function that would send parameters to the generic function "asyncFunc"
async function mySpecificCallFunc(): Promise<Array<CustomType>>
{
  let r = await asyncFunc<CustomType>(new Date(), 'test')
  return []
}

无法从值位置引用类型CustomType [1]。

Flow不希望使用自定义类型。

在C#中,这种通用用法是完全可以接受的,所以我不明白它为什么抱怨?

它给出以下错误:

20:   let r = await asyncFunc<CustomType>(new Date(), 'test')
          ^ Cannot compare boolean [1] to string [2].
References:
20:   let r = await asyncFunc<CustomType>(new Date(), 'test')
          ^ [1]
20:   let r = await asyncFunc<CustomType>(new Date(), 'test')
                                      ^ [2]
20:   let r = await asyncFunc<CustomType>(new Date(), 'test')
                          ^ Cannot reference type `CustomType` [1] from a value position.
References:
3: declare type CustomType = {
            ^ [1]

更新:“CustomType”和请求参数之间目前没有链接。在现实世界中,它看起来像这样:

call: DbRetrieve('type1', param1, param2)
return: [{ _type: 'type1', prop1: true, prop2:'b' }] // an array containing <CustomType> objects

如您所见,没有可以从函数asyncFunc的参数定义的“形状”,因为参数并不总是链接到返回对象的属性。

这是一个类似ORM的调用,我只是希望能够指定类型而不做一些“暴力投射”,但我可能会遵循错误的路径,因为无法从使用中推断出类型...

javascript generics types flowtype
1个回答
1
投票
  1. 您无法直接在通话中指定类型。
  2. 你的CustomType是一个对象,但在代码中你期望一个boolean

因此,首先,您需要在传入和传出数据之间建立链接:

async function asyncFunc<T>(p: T):Promise<T[]> {
  return []
}

函数声明中的<T>就像声明一个变量一样,但p: T:Promise<T[]>会产生依赖关系

其次,你需要通过T使async function asyncFunc<T: CustomType>...有点狭窄。并改变你的type CustomType = boolean;

之后,你只需要打电话给await asyncFunc(true);而不打字。

UPD: 你试图指定一个函数应该返回的类型,只是在函数调用上 - 它不是正确的方式而不是流程而不是JS。函数结果类型应该在函数声明点上声明 - 它可以是几种类型组合的单一类型(type0 | type)。

通用类型用于建立参数和结果之间的关系。所以,你可以,例如,创建一个获取参数的函数,并返回一个相同类型值的数组,如function doSmt<T>(a: T): T[] {return [a];}

我不确定你到底要做什么,但也许你需要这样的东西:

type CustomType<A, B> = {
  prop0: A,
  prop1: B,
}
function asyncFunc<C: string, D: number>(foo: C, bar: D): CustomType<C, D> {  
  // some actions
}
© www.soinside.com 2019 - 2024. All rights reserved.