yewstack / yew-autoprops

Apache License 2.0
8 stars 1 forks source link

Make generics work #1

Closed kirillsemyonkin closed 1 year ago

kirillsemyonkin commented 1 year ago

As of writing the issue, yew-autoprops does not support generics.

Example 1:

#[autoprops_component]
pub fn Example<T: PartialEq + 'static>() -> Html {
    html! {
    }
}

#[function_component]
pub fn App() -> Html {
    html! {
        <Example<u64> />
    }
}

Errors:

struct takes 0 generic arguments but 1 generic argument was supplied

Probable reasons:

Example 2:

#[autoprops_component]
pub fn Example<T: PartialEq + 'static>(t: &T) -> Html {
    html! {
    }
}

#[function_component]
pub fn App() -> Html {
    html! {
        <Example<u64> t={ 0 } />
    }
}

Errors:

cannot find type `T` in this scope

Probable reasons:

Possible solution

This appears to be solvable by copying the generic clause (<T: PartialEq + 'static>) over to both generated component fn (as-is) and generated Props struct (if individual generic parameters are used); as well as copying the clause to the component fn Props param's type, modified to contain only the type names (<T>).

Example 1:

#[derive(PartialEq, Properties)]
pub struct ExampleProps {
    // alternatively, `pub struct ExampleProps<T: PartialEq + 'static>`,
    // but then it would need `#[prop_or_default] pub T: PhantomData<T>` as a hack
}

#[function_component]
pub fn Example<T: PartialEq + 'static>(ExampleProps {}: &ExampleProps) -> Html {
    html! {
    }
}

#[function_component]
pub fn App() -> Html {
    html! {
        <Example<u64> />
    }
}

Example 2:

#[derive(PartialEq, Properties)]
pub struct ExampleProps<T: PartialEq + 'static> {
    t: T,
}

#[function_component]
pub fn Example<T: PartialEq + 'static>(ExampleProps { t }: &ExampleProps<T>) -> Html {
    html! {
    }
}

#[function_component]
pub fn App() -> Html {
    html! {
        <Example<u64> t={ 0 } />
    }
}
valyagolev commented 1 year ago

Should work in HEAD