我正在用TypesScript构建一个Next.js应用程序,其中一种类型是:
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;
}
我想更改它,使locale
、locales
和defaultLocale
永远不是undefined
,以避免在任何地方编写as string
和as string[]
强制转换,因为在我的应用程序中,区域设置总是被定义的.
我试着创建一个这样的类型
type LocaleConfig = {
locale: string
defaultLocale: string
locales: string[]
}
然后只需使用
export const getStaticProps: GetStaticProps = (
context: GetStaticPropsContext & LocaleConfig
) { // do stuff }
但我得到了Type 'string | undefined' is not assignable to type 'string'.
个错误.
我还试图创建一个扩展GetStaticPropsContext
的接口,但除非我误解了它的工作原理,否则我还必须复制如下所示的泛型(这并不理想):
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[]
}