我如何使用打字稿在 Nextjs 的 getServerSideProps 中输入类型?

YMJ*_*YMJ 13 typescript reactjs next.js

我正在使用 NextJs + TypeScript 制作一个小型克隆项目,但我在输入getServerSideProps. 正如您所看到的,在 中getServerSideProps,我正在使用 with 获取数据context.query。但有些错误消息尚未修复,我不明白为什么会出现该错误。

错误信息是这样的。

在此输入图像描述

Type 'string[]' cannot be used as an index type.ts(2538)
Type 'undefined' cannot be used as an index type.ts(2538)
const genre: string | string[] | undefined
Run Code Online (Sandbox Code Playgroud)

我该如何解决这种类型的问题?

Type 'string[]' cannot be used as an index type.ts(2538)
Type 'undefined' cannot be used as an index type.ts(2538)
const genre: string | string[] | undefined
Run Code Online (Sandbox Code Playgroud)

Meh*_*ray 14

你可以这样使用;

type PageProps = {
  isAuthanticated: boolean,
  categories?: CategoryType[]
}

export const getServerSideProps: GetServerSideProps<PageProps> = async (context) => {
  const _props: PageProps = {
    isAuthanticated: auth,
    categories: data.results
  }
  return { props: _props }
};

const Category: NextPage<PageProps> = (props) => {
  return(
    ...
  )
};
Run Code Online (Sandbox Code Playgroud)


Sam*_*l G 1

当您通过上下文接收参数时,该值可能是stringor string[](或未定义),因此您需要进行强制转换。URL 中可以是单个流派或多个流派。

?genre=film或者?genre=film&genre=music

对于您的情况,只需将其转换为字符串:

const genre = context.query.genre as string;
Run Code Online (Sandbox Code Playgroud)

更新

根据您的评论,您在问题中提出的第一个问题实际上是关于如上所述的转换string

第二个问题,您实际上不应该看到,并且必须是 TS 或模块配置问题,与尝试通过导出的普通对象上的索引以字符串形式访问密钥有关"../utils/requests";

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ fetchTrending: { title: string; url: string; }; ...
Run Code Online (Sandbox Code Playgroud)

您的数据对象具有文字键名称:

// ../utils/requests
export default { 
   fetchTrending: { 
      title: "Trending", 
      url: /trending/all/week?api_key=${API_KEY}&language=en-US, 
   }, 
   fetchTopRated: { 
      title: "Top Rated", 
      url: /movie/top_rated?api_key=${API_KEY}&language=en-US, 
   }, 
};
Run Code Online (Sandbox Code Playgroud)

而是像这样定义类型:

export interface IRequest {
  [name: string]: {
    title: string;
    url: string;
  };
}

const data: IRequest = {
  fetchTrending: {
    title: "Trending",
    url: `/trending/all/week?api_key=${API_KEY}&language=en-US1`
  },
  fetchTopRated: {
    title: "Top Rated",
    url: `/movie/top_rated?api_key=${API_KEY}&language=en-US`
  }
};

export default data;

Run Code Online (Sandbox Code Playgroud)

或者您可以使用 Record 来拥有强类型键:

type RequestNames = "fetchTrending" | "fetchTopRated";

export const records: Record<
  RequestNames,
  {
    title: string;
    url: string;
  }
> = {
  fetchTrending: {
    title: "Trending",
    url: `/trending/all/week?api_key=${API_KEY}&language=en-US1`
  },
  fetchTopRated: {
    title: "Top Rated",
    url: `/movie/top_rated?api_key=${API_KEY}&language=en-US`
  }
};
Run Code Online (Sandbox Code Playgroud)