D Lav
D Lav

Reputation: 17

How to create properties of an interface based on another interface dynamically?

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

Answers (1)

Mirco S.
Mirco S.

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>;

Playground

Upvotes: 2

Related Questions