Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is it possible to define types based on an object?

I was wondering if it’s possible to take an object literal and derive types from it. ie.

const inputs = [
  {
    name: "announcements",
    type: "list",
    subFields: [
      {
        name: "copy",
        type: "string",
        defaultValue: "",
      },
      {
        name: "buttonLabel",
        type: "string",
        defaultValue: "",
      },
      {
        name: "buttonUrl",
        type: "url",
        defaultValue: "",
      },
    ],
  },
]

Could I have it automatically inferred as:

interface Announcements {
  copy: string;
  buttonLabel: string;
  buttonUrl: string;
}
type AnnouncementList = Announcements[];

This would be nice because me definitions need to be defined a particular way and rather than redefining them (and possibly making a mistake) it’s much easier if inferred.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Type manipulation in TypeScript does allow us to create types based on other types like the one you showed in your question. Since the keys of Announcements are string literals in the object, we need to use as const to preserve the narrowed string literal types.

const inputs = [
  {
    name: "announcements",
    type: "list",
    subFields: [
      {
        name: "copy",
        type: "string",
        defaultValue: "",
      },
      {
        name: "buttonLabel",
        type: "string",
        defaultValue: "",
      },
      {
        name: "buttonUrl",
        type: "url",
        defaultValue: "",
      },
    ],
  },
] as const

Now we can build a new type based on the type of inputs.

type Announcements = {
  [K in typeof inputs[0]["subFields"][number]["name"]]: string
}

// type Announcements = {
//     copy: string;
//     buttonLabel: string;
//     buttonUrl: string;
// }

Playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading