Argument of type ‘readonly X’ is not assignable to parameter of type ‘X’.

huangapple go评论65阅读模式
英文:

Argument of type 'readonly X' is not assignable to parameter of type 'X'

问题

这是你想要的翻译内容:

原始代码中,我使用了一个第三方库,其中有这个类:

export class Foo {
  field: X[];
  .
}

我在我的代码中使用了这个类型:

print(foo.field)

现在,新版本中对field的定义已更改为:

export class Foo {
  readonly foo: readonly X[];
  .
}

因此,我的代码抛出了一个错误:

类型参数 'readonly X' 不能分配给类型参数 'X'。

这是我的函数:

function print(foo: Foo[]): string {
  return //处理foo,返回某种形式的字符串
}

我想知道如何修复这个错误?

英文:

I was using a third-party library that has this class:

export class Foo {
  field: X[];
  ….
}

I was consuming this type in my code:

print(foo.field)

now with a new version the field definition changed to this

export class Foo {
  readonly foo: readonly X[];
  ….
}

so my code throws an error:

> Argument of type 'readonly X' is not assignable to parameter of type
> 'X'.

here is my function:

function print(foo: Foo[]): string {
  return //process foo, return some form of string
}

I wonder how to fix that error?

答案1

得分: 1

如果您不对传递给您的函数的数组进行更改,那么您还应将 readonly 添加到它上面:

function print(foo: readonly Foo[]): string {
  return //处理 foo,返回某种字符串形式
}

使用 readonly type[] 是告诉 TypeScript 一个数组应该是只读的,并且不会被修改的一种方式。TypeScript 通过仅暴露该数组上的只读方法并禁止对其进行赋值来强制执行这一点:

const myArray: readonly string[] = [];
myArray[0] = 's';
// 类型 'readonly string[]' 的索引签名仅允许读取。(2542)
myArray.push('a');
// 类型 'readonly string[]' 上不存在属性 'push'。(2339)

readonly type[] 等同于 ReadonlyArray<type>,您可以在Typescript文档中找到更多解释。

英文:

If you are not mutating the array passed to your function, then you should add readonly to it as well:

function print(foo: readonly Foo[]): string {
  return //process foo, return some form of string
}

Using readonly type[] is a way to tell Typescript that an array is expected and that this array will not be modified. Typescript enforces this by exposing only read-only methods on this array and disallow assignment to it:

const myArray: readonly string[] = [];
myArray[0] = &#39;s&#39;
// Index signature in type &#39;readonly string[]&#39; only permits reading.(2542)
myArray.push(&#39;a&#39;)
// Property &#39;push&#39; does not exist on type &#39;readonly string[]&#39;.(2339)

readonly type[] is equivalent to ReadonlyArray&lt;type&gt; and you can find more explanations in Typescript docs.

huangapple
  • 本文由 发表于 2023年2月6日 14:22:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/75357966.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定