Understanding Mapped Types in TypeScript
Exploring the concept of mapped types in TypeScript can be quite enlightening. The TypeScript documentation provides a neat example to get you started:
type Proxy<T> = {
get(): T;
set(value: T): void;
}
type Proxify<T> = {
[P in keyof T]: Proxy<T[P]>;
}
function proxify<T>(o: T): Proxify<T> {
// ... creating proxies here ...
}
let proxyProps = proxify(props);
Now, let's dive into understanding how exactly you would implement the proxify function.
Application in Real Life Scenarios
Consider an application scenario where you have defined types like User and FormField as follows:
interface User extends BaseRecord {
readonly 'id': number;
readonly 'name'?: string;
}
interface FormField<T> {
readonly value: T;
readonly edited: boolean;
}
type WrappedInFormField<T> = {
[P in keyof T]: FormField<T[P]>;
};
Now, your objective is to create a function with the signature below for wrapping objects:
const wrap = <T>(o: T): WrappedInFormField<T> => {
// ...Your implementation goes here...
}
wrappedUser: WrappedInFormField<User> = wrap<User>(UserIJustGotFromApi);
How do you think you should proceed with this task?