microsoft / microsoft/TypeScript

Cannot assign readonly statics in static blocks

オープン
#56,584 コメント 4 件 リアクション 1 件 担当者 1 名 GitHub で見る

@rbuckton がすでに取り組んでいます。

2023年11月29日 から。

Needs Investigation
主要言語
Go
スター
111k
フォーク
14.4k
平均マージ
1日 19時間
マージ済み PR(30日)
117

説明

🔍 Search Terms

"assign readonly static in static block", "assign readonly static in static constructor"

✅ Viability Checklist
⭐ Suggestion

static readonly fields should be assignable within static code blocks, similar to how readonly fields are assignable in constructors. I've had a read through various issues, and those around the MR that introduced support for static blocks, but found no mention of dealing with readonly fields.

📃 Motivating Example

I'm making a variation on ringbufferjs, here, this.headerSize = ... shows an error without the //@ts-expect-error

type TypedArray =
  | Float32Array
  | Float64Array
  | Int8Array
  | Int16Array
  | Int32Array
  | BigInt64Array;
type TypedArrayConstructor =
  | Float32ArrayConstructor
  | Float64ArrayConstructor
  | Int8ArrayConstructor
  | Int16ArrayConstructor
  | Int32ArrayConstructor
  | BigInt64ArrayConstructor;

export default class LiveRingBuffer {
  private static readonly headerSize: number;

  static {
    const writePtrWidth = Uint32Array.BYTES_PER_ELEMENT;
    const readPtrWidth = Uint32Array.BYTES_PER_ELEMENT;
    const lapPtrWidth = Uint32Array.BYTES_PER_ELEMENT;
    //@ts-expect-error
    this.headerSize = writePtrWidth + readPtrWidth + lapPtrWidth;
  }

  static getStorageForCapacity(
    capacity: number,
    type: TypedArrayConstructor,
  ): SharedArrayBuffer {
    if (!type.BYTES_PER_ELEMENT) {
      throw TypeError('Pass in a ArrayBuffer subclass');
    }
    const storageWidth = (capacity + 1) * type.BYTES_PER_ELEMENT;
    const alignedHeaderWidth =
      Math.ceil(this.headerSize / type.BYTES_PER_ELEMENT) *
      type.BYTES_PER_ELEMENT;

    const bytes = alignedHeaderWidth + storageWidth;
    return new SharedArrayBuffer(bytes);
  }

  // ...
}
💻 Use Cases
  1. What do you want to use this for?
    See "Motivating Example"
  2. What shortcomings exist with current approaches?
    Current approach suppresses readonly error; alternative is to remove the readonly keyword, also not ideal since it really is readonly/const
  3. What workarounds are you using in the meantime?
    //@ts-expect-error hides the error and emits the desired code.

コントリビューションガイド

コントリビューションガイドを開く

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

評価

この issue はまだ評価されていません。

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。