0

So I have this code:

import * as Icons from "../../icons"

const Icon = ({ icon, ...props }) => {
  const Icon = Icons[icon]
  return <Icon {...props} />
}

and I am trying to find the correct types for it but no matter what I do, it won´t work. Pls HELP

My errors:

enter image description here 2 3

2 Answers 2

1

Declare an interface for the Icons import by import * as Icons from './icons' statement.

./icons/SquareIcon.tsx:

import React from 'react';

export default function SquareIcon() {
  return <div>square icon</div>;
}

./icons/CycleIcon.tsx:

import React from 'react';

export default function CycleIcon() {
  return <div>cycle icon</div>;
}

./icons/index.ts:

import CycleIcon from './CycleIcon';
import SquareIcon from './SquareIcon';

export interface IconType {
  cycle: typeof CycleIcon;
  square: typeof SquareIcon;
}

export { CycleIcon as cycle, SquareIcon as square };

Icon.tsx:

import React from 'react';
import * as Icons from './icons';
import type { IconType } from './icons';

const Icon = ({ icon, ...props }: { icon: keyof IconType }) => {
  const Icon = Icons[icon];
  return <Icon {...props} />;
};

function Test() {
  return <Icon icon="cycle"></Icon>;
}
Sign up to request clarification or add additional context in comments.

Comments

0

Specify the data types as follows,

const Icon = ({ icon , ...props } : {icon : string , props : any}) => {
    const Icon = Icons[icon]
    return <Icon {...props} />
}

If the data has only one type you can use the proper data type without using any.

6 Comments

thanks, but I still get the Element "implicitly has an 'any' type because expression of type 'any' can't be used to index type 'typeof" error in the second line of code.
what is the data type of icon param. Is it a number
the type is string
did you try replacing any with string for icon param ?
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'typeof import("")'. No index signature with a parameter of type 'string' was found on type 'typeof import("")'.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.