TypeScript Computed Property Types
In TypeScript, you can often define object types where the keys are dynamic or based on other values. This is particularly useful when working with enums, union types, or when you need to create mappings. This challenge will test your understanding of how to dynamically generate property keys within TypeScript type definitions.
Problem Description
Your task is to create a TypeScript type that can represent an object where the keys are derived from a union of string literals, and the values are of a specific type. This is often referred to as a "mapped type" or a type with "computed property names" at the type level.
You will be given a union of string literals and a type for the property values. You need to define a generic type MappedObject<T, V> where:
Tis a union of string literals (e.g.,"a" | "b" | "c").Vis the type for the values of the properties.
The resulting MappedObject<T, V> type should describe an object where each member of the union T becomes a key, and each of these keys has a value of type V.
Key Requirements:
- Define a generic TypeScript type
MappedObject<T, V>. Twill be a union of string literals.Vwill be a specific value type.- The output type should have keys corresponding to each string literal in
T, with each key having a value of typeV.
Expected Behavior:
When MappedObject is instantiated with a union of string literals and a value type, it should correctly represent an object with those string literals as keys and the specified value type for all properties.
Edge Cases:
- What happens if the union
Tis empty? (Though for practical purposes, this challenge assumesTwill have at least one literal).
Examples
Example 1:
Input:
T = "name" | "age" | "email"
V = string | number
Output Type:
{
name: string | number;
age: string | number;
email: string | number;
}
Explanation: The type MappedObject<"name" | "age" | "email", string | number> should produce an object type where each literal ("name", "age", "email") becomes a key, and all corresponding values have the type string | number.
Example 2:
Input:
T = "pending" | "fulfilled" | "rejected"
V = boolean
Output Type:
{
pending: boolean;
fulfilled: boolean;
rejected: boolean;
}
Explanation: The type MappedObject<"pending" | "fulfilled" | "rejected", boolean> should create an object where the keys are the status strings, and each status has a boolean value.
Example 3:
Input:
T = "id"
V = number
Output Type:
{
id: number;
}
Explanation: Demonstrates a simple case with a single literal in the union.
Constraints
Twill always be a union of string literals.Vwill be a valid TypeScript type.- The solution should be a single type definition.
Notes
This challenge involves using TypeScript's powerful type manipulation features. Consider how you can iterate over the members of a union type to create new properties. The keyof operator and indexed access types might be relevant, but the core concept here is mapping over a union to create object properties.