React Typescript 101:使用带有常量列表和函数的Typescript



很抱歉问你,在下面的例子中我该如何使用typescript。经过一个小时的努力,我感谢你的帮助!

下面的map函数使用sortOptions,我试图在declare const SortOptionsProps中使用Typescript来定义它们。因此,我很想弄清楚如何将SortOptionsProps传递到下面的export default function Layout()

import { Menu } from '@headlessui/react'
declare const SortOptionsProps: {
name: string
href: string
}[]
const sortOptions = [
{ name: 'Most Popular', href: '#' },
{ name: 'Best Rating', href: '#' },
{ name: 'Newest', href: '#' },
{ name: 'Price: Low to High', href: '#' },
{ name: 'Price: High to Low', href: '#' },
]
export default function Layout() {
return (
<>
{sortOptions.map((option) => (
<Menu.Item key={option}>
{({ active }) => (
<a
href={option.href}
className={classNames(
active
? 'bg-gray-100'
: '',
'block px-4 py-2 text-sm font-medium text-gray-900'
)}
>
{option.name}
</a>
)}
</Menu.Item>
))}      
</>
)
}
type SortOption = { name: string; href: string }:
const sortOptions: SortOption[] = [
{ name: 'Most Popular', href: '#' },
{ name: 'Best Rating', href: '#' },
{ name: 'Newest', href: '#' },
{ name: 'Price: Low to High', href: '#' },
{ name: 'Price: High to Low', href: '#' },
]

如果您愿意,也可以使用interface代替type

interface SortOption { name: string; href: string }

最新更新