0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

TypeScriptでreadonlyのフィールド定義をsetも出来るフィールドに戻す

Last updated at Posted at 2020-11-10
interface ReadonlyFields {
  readonly name: string
  readonly age: number
}

のようなreadonlyがフィールドに指定されている定義から全てのreadonlyを除去する方法の紹介です。

type Assignable<T> = {
  -readonly [P in keyof T]: T[P]
}

// つまり
// Assignable<ReadonlyFields> == {
//   name: string
//   age: number
// }
// になります

このような定義を行えば下のように使えます


const f: Assignable<ReadonlyFields> = {
  name: "Tom",
  age: 20
}
f.name = "Bob"
f.age = 30

余談

CDKでXXXPropsを構築する時にreadonlyを外したくてこの方法を見つけました。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?