Currently, I am developing a Next.js application using TypeScript, and one of the types is as follows:
type GetStaticPropsContext<Q extends ParsedUrlQuery = ParsedUrlQuery, D extends PreviewData = PreviewData> = {
params?: Q | undefined;
preview?: boolean | undefined;
previewData?: D | undefined;
locale?: string | undefined;
locales?: string[] | undefined;
defaultLocale?: string | undefined;
}
To simplify my code and avoid constantly using as string
and as string[]
castings for locale
, locales
, and defaultLocale
, I want to ensure that they are never undefined
. In my application, these values are always defined.
I attempted to create a new type like this:
type LocaleConfig = {
locale: string
defaultLocale: string
locales: string[]
}
Then, I tried using it in the following way:
export const getStaticProps: GetStaticProps = (
context: GetStaticPropsContext & LocaleConfig
) { // do stuff }
However, this resulted in an error stating
Type 'string | undefined' is not assignable to type 'string'.
.
I also experimented with creating an interface that extends GetStaticPropsContext
, but it seems like I would need to duplicate the generics, which is less than ideal:
export interface NewGetStaticPropsContext<
Q extends ParsedUrlQuery = ParsedUrlQuery,
D extends PreviewData = PreviewData
> extends GetStaticPropsContext {
params?: Q | undefined
previewData?: D | undefined
locale: string
defaultLocale: string
locales: string[]
}