Node.js 返回类型不可赋值

Node.js 返回类型不可赋值,node.js,typescript,Node.js,Typescript,第三方软件包的功能如下所示 function asKey(key: KeyObject | KeyInput, parameters?: KeyParameters): RSAKey | ECKey | OKPKey | OctKey; 所有返回类型(RSAKey | ECKey | OKPKey | OctKey)都是扩展Key的接口 我正在使用asKey函数,并尝试设置RSAKey的返回类型,因为我知道它只返回此1接口 private foo = (): RSAKey => {

第三方软件包的功能如下所示

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中。如何才能最好地使此返回类型工作?

当您编写以下代码时

private foo = (): RSAKey => {
    return asKey('foo');
};
Typescript正在查看
asKey
,发现可以返回多个不同的类型,而
foo
无法处理它们,这就是为什么会出现错误

如果您知道
askey
将只返回
RSAKey
类型,则必须告诉typescript:

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

您可以使用关键字
as

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

当您编写以下代码时

private foo = (): RSAKey => {
    return asKey('foo');
};
Typescript正在查看
asKey
,发现可以返回多个不同的类型,而
foo
无法处理它们,这就是为什么会出现错误

如果您知道
askey
将只返回
RSAKey
类型,则必须告诉typescript:

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

您可以使用关键字
as

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