prismicio / prismic-ts-codegen

A Prismic model-to-TypeScript-type generator.
Apache License 2.0
18 stars 6 forks source link

feat: support custom Embed data with provider-specific types #1

Closed angeloashmore closed 2 years ago

angeloashmore commented 2 years ago

Types of changes

Description

This PR adds the ability to type Embed fields with custom provider-specific types.

For example, if you expect YouTube links to be provided via an Embed field, and you know the oEmbed data that will be provided, you can configure the output to include your custom type.

Custom types can be provided to generateTypes()'s fieldConfigs.embed.providerTypes option:

const model = prismicM.model.customType({
    seed: t.title,
    id: "foo",
    fields: {
        bar: prismicM.model.embed({ seed: t.title }),
    },
});

const types = generateTypes({
    customTypeModels: [model],
    fieldConfigs: {
        embed: {
            providerTypes: {
                YouTube: "YouTubeType",
                Vimeo: "VimeoType",
            },
        },
    },
});

This will provide the following output (this is not the full output, only the relevant part):

interface FooDocumentData {
    bar: prismicT.EmbedField<
        prismicT.AnyOEmbed &
            prismicT.OEmbedExtra &
            (
                | ({
                        provider_name: "YouTube",
                  } & YouTubeType)
                | ({
                        provider_name: "Vimeo",
                  } & VimeoType)
            )
    >;
}

The Embed field can then be type-narrowed by checking provider_name against a string constant.

If no provider-specific types are given, the field will be typed as prismicT.EmbedField.

Checklist:

🐦

github-actions[bot] commented 2 years ago

size-limit report 📦

Path Size
dist/index.js 1.04 MB (+0.02% 🔺)
dist/index.cjs 1.04 MB (+0.02% 🔺)