cuddlemeister
cuddlemeister

Reputation: 1785

Create nested TypeScript type from a simple one

I've a model that looks like this

export interface LoremIpsum {

propertyA: string;
propertyB: number;

}

From the server I have the data returned in this format

{
    "Fields": {
        "propertyA": {
            "value": "something"
        },
        "propertyB": {
            "value": 123
        }
    }
}

Is this a way to make the generic type for this? SO I could use it in a way like DynamicResponse<LoremIpsum>?

Upvotes: 0

Views: 33

Answers (1)

lukasgeiter
lukasgeiter

Reputation: 152890

You'll want to use a mapped type to iterate over all keys of the generic type T. You can then map each property type of T to { value: T[K] }

type Fields<T> = {[K in keyof T]: { value: T[K] }};

interface DynamicResponse<T> {
  Fields: Fields<T>
}

Playground

Upvotes: 3

Related Questions