Skip to content

JSON.stringify does not accept readonly Array #1

Closed
@narumincho

Description

@narumincho

🕗 Version

1.0.0

💻 Code

/// <reference path="./node_modules/better-typescript-lib/lib.esnext.full.d.ts" />

const array: number[] = [0, 1, 2];
const readonlyArray: readonly number[] = [0, 1, 2];

JSON.stringify(array);
JSON.stringify(readonlyArray); // type error

🙁 Actual behavior

Compile error at the last line:

No overload matches this call.
  Overload 1 of 2, '(value: JSONValue, replacer?: ((this: JSONValue, key: string, value: JSONValue) => any) | undefined, space?: string | number | undefined): string', gave the following error.
    Argument of type 'readonly number[]' is not assignable to parameter of type 'JSONValue'.
      The type 'readonly number[]' is 'readonly' and cannot be assigned to the mutable type 'JSONValue[]'.
  Overload 2 of 2, '(value: JSONValue, replacer?: (string | number)[] | null | undefined, space?: string | number | undefined): string', gave the following error.
    Argument of type 'readonly number[]' is not assignable to parameter of type 'JSONValue'.
      The type 'readonly number[]' is 'readonly' and cannot be assigned to the mutable type 'JSONValue[]'.ts(2769)

🙂 Expected behavior

no compile error

🛠 Workaround

JSON.stringify(readonlyArray as JSONValue);

Basically it feels a bit inconvenient for those who want to use ReadonlyArray for arrays.

とすればエラーは消えるけど, 基本的に 配列に ReadonlyArray を 使いたい身としては少し不便に感じる気がします.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions