【问题标题】:How to cast two flow types with a maybe attribute如何使用可能属性强制转换两种流类型
【发布时间】:2018-10-31 00:24:09
【问题描述】:

我想将 RedisGetHashJob 强制转换为 RedisKey 类型,但出现错误...

我的类型:

export type RedisKey = {
  source: string,
  destination: string,
  type: string,
  id: string,
  groupId: string,
  pid?: string,
};

export type RedisGetHashJob = {
  source: string,
  destination: string,
  type: string,
  id: string,
  groupId: string,
  pid: string,
};

我有两个功能:

1 - 函数 createKey(obj: RedisKey): 字符串

2 - 函数 getHashJob(obj: RedisGetHashJob): 承诺

在我的第二个函数中,必须设置 pid 属性。但是当我尝试这样称呼它时:

function getHashJob(obj: RedisGetHashJob): Promise<string> {
  const key = createKey(obj);
  ....
}

我有以下错误:

Error: src/common/lib/redis.js:60
 60:   const key = createKey(obj);
                             ^^^ object type. This type is incompatible with the expected param type of
 15: export function createKey(obj: RedisKey): string {
                                    ^^^^^^^^ object type
  Property `pid` is incompatible:
      8:   pid?: string,
                 ^^^^^^ undefined. This type is incompatible with. See: src/types/redis.js:8
     26:   pid: string,
                ^^^^^^ string. See: src/types/redis.js:26

你知道完成这项工作的好方法吗?

问候,

【问题讨论】:

    标签: ecmascript-6 flowtype


    【解决方案1】:

    发生这种情况是因为您可以删除RedisKey 对象中的pid 属性,它仍然是RedisKey 对象,但不再是RedisGetHashJob。 如果您的createKey 看起来像

    function createKey(obj: RedisKey): string {
      delete obj.pid
      return 'a';
    }
    

    要解决这个问题,您可以在将 obj 传递给 createKey 之前复制它:

    function getHashJob(obj: RedisGetHashJob): Promise<string> {
      const objCopy = {...obj}
      const key = createKey(objCopy);
      ...
    }
    

    Try it out

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-24
      • 2012-09-12
      • 2021-08-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-10
      • 1970-01-01
      相关资源
      最近更新 更多