benjamincanac / ui3

A UI Library for Modern Web Apps, powered by Vue & Tailwind CSS.
https://ui.nuxt.com
MIT License
54 stars 8 forks source link

fix(FormField): added a utility type to fix some type errors #81

Closed mauroerta closed 4 months ago

mauroerta commented 4 months ago

๐Ÿ”— Linked issue

No Linked Issue (I can create one in case it is needed)

โ“ Type of change

๐Ÿ“š Description

I wanted to contribute to this project, specifically, I wanted to pick this issue here, while working on it I saw the @ts-expect-error comments and I thought I could fix them easily in a separate PR since they're all related to the same error.

The Problem

In 2 places the type definition was accepting a generic parameter T without any constraint and trying to access one of its properties:

type Props<T> = {
   size?: T['size'] // <-- You can't assume T is an object and that it might have a property called "size"
}

Solution

I thought about 2 approaches:

Solution 1. (Proposed solution)

Instead of accessing the property directly (T['size']) we can use a utility type that extracts the property value in case it exists:

type Props<T> = {
   size?: GetObjectField<T, 'size'>
}

The utility type GetObjectField extracts the type of size contained in the type T in case T is object-like, never is returned otherwise.

I'm not sure GetObjectField is the right name for this utility type, in case this approach will be chosen we can think of another name

Solution 2

Simply constraint the type of the generic parameter:

type Props<T extends { size?: string }> = {
   size?: T['size']
}

This is the simplest way to fix it but I'm not aware if this was not done for some reason.

I chose to go for the Solution 1 because I didn't have to change anything in the type definition of the affected types, even though usually I'd have chosen the Solution 2

๐Ÿ“ Checklist

benjamincanac commented 4 months ago

Thank you!! Didn't know how to fix that ๐Ÿ˜… I saw you mentioned nuxt/ui#2140, it would be really helpful if you have a solution ๐Ÿ˜Š

mauroerta commented 4 months ago

Thank you!! Didn't know how to fix that ๐Ÿ˜… I saw you mentioned nuxt/ui#2140, it would be really helpful if you have a solution ๐Ÿ˜Š

I'll work on it, I hope to open a PR soon