expo / vector-icons

https://icons.expo.fyi
MIT License
647 stars 114 forks source link

Better way to extract Icon type #163

Closed nobobo1234 closed 3 years ago

nobobo1234 commented 3 years ago

When one uses @expo/vector-icons with typescript one runs into an issue with the typing accesibility of the Icon class. Let's say one makes a component which takes in a name for an icon and returns a MaterialIcon component with that name and a specific size.

import * as React from 'react';

import { MaterialIcons } from '@expo/vector-icons';

const Icon = ({ name }: { name: string }) => <MaterialIcons size={30} name={name} />;

export default Icon;

Typescript gives an error here that the string type is not compatible with the type of Icon<all the icon name strings>. The Icon type, nor the MaterialIcon type is not exported however, which make this issue hard to fix. One has to dive into the internal exports and get the Icon type from the createIconSet file in the build and create the MaterialIcon type from there.

import type {Icon as Icon_} from "@expo/vector-icons/build/createIconSet";

type IconType = typeof MaterialIcons extends Icon_<infer Type, string> ? Type : never;

This should be easier to do imo.

de1ay commented 3 years ago

You can use the approach from #153