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 1 year has passed since last update.

【TypeScript】配列の要素をキーとするオブジェクトを生成したい

Last updated at Posted at 2022-05-24

お断り

2022/5/25現在未解決です。

対処フロー

  1. 文字列リテラルの配列を定義する
  2. 配列をもとにUnion Typeを定義する
  3. 2.のUnion Typeをキーとするプロパティを持つTypeを定義する
  4. 3.のTypeを満たすオブジェクトを、1.で定義した配列をもとに作りたい
  5. 配列からオブジェクトにするには、Object.fromEntriesが有効
  6. 作ってみたが、戻り値の型が{[x: string]: any}で型一致させられなかった

コードベース

// 1.
const foo = ["a", "b", "c"] as const;
// 2.
type Foo = typeof foo[number];
// type Foo = "a" | "b" | "c"
// 3.
type Bar = {
   [key in Foo]: () => void // プロパティの型は適当
}
// type Bar = { "a" | "b" | "c" : () => void }
// 4.
// 1.の配列と別の何かしらを組み合わせて、こんな感じのオブジェクトを作りたい
// const bar = {
//   a: () => {console.log("hello")},
//   b: () => {console.log("hello")},
//   c: () => {console.log("hello")}
// }
// 5.
// Object.fromEntriesで作ること自体はできる
const greet = () => {console.log("hello")};
const bar: Bar = Object.fromEntries(foo.map(el => [el, greet]));
// 6.
// しかしObject.fromEntries()の戻り値の型は{[x: string]: any}だったので、type barと一致させられなかった

現状の結論: as

- const bar: Bar = Object.fromEntries(foo.map(el => [el, greet]));
+ const bar: Bar = Object.fromEntries(foo.map(el => [el, greet])) as Bar;

引き続き模索します。

0
0
4

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?