49m

以下の TypeScript のコード const data = Object.freeze({ hoge: Object.freeze({ a: 1, b: 2, }), fuga: Object.freeze({ x: 3, y: 4, }), }); function foo(key: keyof typeof data) { return data[key]; } 現状では foo の返り値の型は hoge の型と fuga の型のORになっているが、これをkeyの値に応じて一方だけが返るようにしたい。どうすればいい?

Answer
To make the return type of the foo function depend on the specific key passed as an argument, you can use conditional types with TypeScript. Here's how you can modify the foo function to achieve this:
typescript
const data = Object.freeze({ hoge: Object.freeze({ a: 1, b: 2, }), fuga: Object.freeze({ x: 3, y: 4, }), }); function foo<K extends keyof typeof data>(key: K): (typeof data)[K] { return data[key]; }
In this modified version, we've made the following changes:
  1. We've added a generic type parameter K that extends keyof typeof data14.
  2. We've specified the return type as (typeof data)[K], which means the function will return the type of the property accessed by the key K14.
Now, when you call the foo function with a specific key, TypeScript will infer the correct return type:
typescript
const hogeResult = foo('hoge'); // Type is { readonly a: number; readonly b: number; } const fugaResult = foo('fuga'); // Type is { readonly x: number; readonly y: number; }
This approach uses TypeScript's ability to infer the correct type based on the literal value passed as the key. The function will now return the exact type of the object property corresponding to the given key, rather than a union of all possible types14. Additionally, since we're using Object.freeze, the returned objects will be readonly, which is correctly reflected in the inferred types25.
Related
Conditional Return Typesを使用する具体的な方法は
TypeScriptの型推論でよくあるエラーの解決方法は
Object.freezeとconstアサーションの違いは
TypeScriptのkeyofとtypeofの使い方は
TypeScriptのTuple型の使い方と注意点は
javascript.plainenglish.io
View More