Sergino
Sergino

Reputation: 10838

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

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?

Upvotes: 0

Views: 1337

Answers (1)

Valentin
Valentin

Reputation: 11802

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] = 's'
// Index signature in type 'readonly string[]' only permits reading.(2542)
myArray.push('a')
// Property 'push' does not exist on type 'readonly string[]'.(2339)

readonly type[] is equivalent to ReadonlyArray<type> and you can find more explanations in Typescript docs.

Upvotes: 1

Related Questions