-1

I'm newbie at typescript and my codes:

type searchParamsProps = {
  manufacturer: string,
  model: string,
  year: number,
  fuel: string,
  limit: number,
}

export default async function Home({ searchParams }: searchParamsProps) {
  const allCars = await fetchCars({
    manufacturer: searchParams.manufacturer || "",
    model: searchParams.model || "",
    year: searchParams.year || 2022,
    fuel: searchParams.fuel || "",
    limit: searchParams.limit || 10,
  });

What is typeof of searchParams? I tried to describe the types with with string, number, or union, but how to type it correctly?

VSCode Intellisense says:

Property 'searchParams' does not exist on type 'searchParamsProps'.ts(2339)

(parameter) searchParams: any
InSho
  • 1
  • 4
  • This is a typo, your line should read: `export default async function Home({ searchParams }: { searchParams: searchParamsProps } ) {` or move the type definition of the props elsewhere or use something like [this](https://stackoverflow.com/questions/59988667/typescript-react-fcprops-confusion) – Harrison Sep 01 '23 at 13:27
  • @Harrison Or instead of building an object just to destructure it: `Home(searchParams: searchParamsProps)` – DBS Sep 01 '23 at 13:30
  • Does this answer your question? [Object destructuring syntax - ES6](https://stackoverflow.com/questions/31915621/object-destructuring-syntax-es6) – Jared Smith Sep 01 '23 at 14:04
  • @Harrison thanks for your advice, now typescript seem to be happy again. – InSho Sep 02 '23 at 11:53

3 Answers3

0

{ ... } = foo is a destructuring operation. When you do { searchParams }: searchParamsProps, this means you want to extract the member called searchParams from searchParamsProps. However, searchParamsProps does not have a member called searchParams, therefore it does not have a type, since it doesn't even exist.

starikcetin
  • 1,391
  • 1
  • 16
  • 24
0

If you want to keep the destructuring syntax of searchParams you could define the type of the parameter object as {searchParams: searchParamsProps;}.

export default async function Home({
  searchParams
}: {
  searchParams: searchParamsProps;
}) {
  const allCars = await fetchCars({
    manufacturer: searchParams.manufacturer || "",
    model: searchParams.model || "",
    year: searchParams.year || 2022,
    fuel: searchParams.fuel || "",
    limit: searchParams.limit || 10
  });
}

TypeScript Playground

Behemoth
  • 5,389
  • 4
  • 16
  • 40
0

Try to use generic types in Typescript: Reference Link

function identity<Type>(arg: Type): Type {
  return arg;
}