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.
CodePudding user response:
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;
// }