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の値に応じて一方だけが返るようにしたい。どうすればいい?
以下の 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の値に応じて一方だけが返るようにしたい。どうすればいい?
Sources
Answer
To make the return type of the
In this modified version, we've made the following changes:
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
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:
typescriptconst 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]; }
- We've added a generic type parameter
K
that extendskeyof typeof data
14. - We've specified the return type as
(typeof data)[K]
, which means the function will return the type of the property accessed by the keyK
14.
foo
function with a specific key, TypeScript will infer the correct return type:
typescriptconst hogeResult = foo('hoge'); // Type is { readonly a: number; readonly b: number; } const fugaResult = foo('fuga'); // Type is { readonly x: number; readonly y: number; }
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型の使い方と注意点は