【问题标题】:Return type is not assignable返回类型不可分配
【发布时间】:2020-06-09 21:13:01
【问题描述】:

第 3 方包具有如下所示的功能...

function asKey(key: KeyObject | KeyInput, parameters?: KeyParameters): RSAKey | ECKey | OKPKey | OctKey;

所有返回类型 (RSAKey | ECKey | OKPKey | OctKey) 都是扩展 Key 的接口。

我正在使用asKey 函数并尝试设置RSAKey 的返回类型,因为我知道它只返回这1 个接口...

private foo = (): RSAKey => {
    return asKey('foo');
};

但是这失败了:

Type 'RSAKey | ECKey | OKPKey | OctKey' is not assignable to type 'RSAKey'.
  Type 'ECKey' is not assignable to type 'RSAKey'.
    Types of property 'kty' are incompatible.
      Type '"EC"' is not assignable to type '"RSA"'.ts(2322)

如果我在 foo 函数中将返回类型更改为 Key,我不会收到任何错误,但这不是我想要的,因为 RSAKey 有一个我想调用的额外函数,它不在 Key 中。我怎样才能最好地让这种返回类型发挥作用?

【问题讨论】:

    标签: node.js typescript


    【解决方案1】:

    当你在写下面的代码时

    private foo = (): RSAKey => {
        return asKey('foo');
    };
    

    Typescript 正在查看 asKey 并发现可以返回多种不同的类型,而 foo 不处理它们,这就是您收到错误的原因。

    如果你知道 askey 将只返回一个 RSAKey 类型,你必须告诉 typescript:

    没关系,我知道发生了什么。相信我,类型是 RSAKey

    你使用关键字as来做到这一点

    private foo = (): RSAKey => {
        return asKey('foo') as RSAKey;
    };
    

    【讨论】:

      猜你喜欢
      • 2021-07-27
      • 1970-01-01
      • 1970-01-01
      • 2019-10-13
      • 2013-10-26
      • 2020-03-07
      • 2020-04-02
      • 2019-06-02
      • 1970-01-01
      相关资源
      最近更新 更多