1
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.

Object.keysのreturn valueに型をつける関数

Last updated at Posted at 2023-01-21

はじめに

Object.keys()の返り値の型がstring[]になるのを避ける策として型アサーションがありますが、
ソースコードに型アサーションをあまり増やしたくない。。その解決策メモ

問題点

string[]が型推論される

const user = {
  name: "abc",
  age: 10
}

const keys = Object.keys(user) // string[]
const assertKeys = Object.keys(user) as (keyof typeof user)[] // ("name" | "age")[]

解決策

Object.keysをラップした関数を作成する
内部でType Assertionsを使用する

const myObjectKeys = <T extends Record<string, unknown>>(obj: T)=> Object.keys(obj) as (keyof T)[]

const keys = myObjectKeys(user) // ("name" | "age")[]

参考文献

TypeScript Documentation

1
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
1
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?