Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React Typescript 101: Using Typescript with const list and function

I’m sorry to ask, but how would I use typescript in the example below. After an hour of trying, I appreciate your help!

The map function below uses sortOptions and I tried to define them using Typescript in declare const SortOptionsProps. As such, I would love to figure out how to pass SortOptionsProps to export default function Layout() below.

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>
        ))}      
    </>
    )
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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: '#' },
]

You could also use interface in place of type if you prefer.

interface SortOption { name: string; href: string }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading