Reputation: 17
I want to create an Interface based on another Interface.
Let's say I have a data interface that looks like this:
interface SimpleData {
uid: number;
name: string;
email: string;
}
And I want to create another interface that represents a validated SimpleData
object, like this:
interface ValidatedSimpleData {
uid: { value: SimpleData["uid"], error: boolean };
name: { value: SimpleData["name"], error: boolean };
email: { value: SimpleData["email"], error: boolean };
}
Is there is a way to create the properties of ValidatedSimpleData
dynamically based on the properties defined in SimpleData
?
Upvotes: 1
Views: 56
Reputation: 2640
You do this via mapped types.
A mapped type is a generic type which uses a union created via a keyof to iterate through the keys of one type to create another:
interface SimpleData {
uid: number;
name: string;
email: string;
}
type Validated<T> = {
[K in keyof T]: {
value: T[K],
error: boolean
}
}
type ValidatedSimpleData = Validated<SimpleData>;
Upvotes: 2