Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to join arrays without losing type information? #120

Open
jons-bakerhill opened this issue Jun 14, 2024 · 2 comments
Open

How to join arrays without losing type information? #120

jons-bakerhill opened this issue Jun 14, 2024 · 2 comments

Comments

@jons-bakerhill
Copy link

I have the following template code

{{- publicProperties = class.Properties | Custom.HasPublicSetter
    if (class.BaseClass?.Properties)
        publicProperties = Array.AddRange(publicProperties, class.BaseClass?.Properties | Custom.HasPublicSetter)
    end
    referencedClassTypes = publicProperties | Custom.GetClassTypes
}}

where GetClassTypes is defined as
public static IEnumerable<IType> GetClassTypes(IEnumerable<IProperty> publicProperties)

When rendering I get the error "Unable to convert type range to IEnumerable<IProperty>"

Is there a way to join arrays and keep type information?

@jons-bakerhill
Copy link
Author

I got things to work via the code below, would be nice to know if there's a better way though.

        public static IEnumerable<IType> GetClassTypes(object publicProperties)
        {
            IEnumerable<IProperty> cast = publicProperties as IEnumerable<IProperty>
                ?? (publicProperties as IEnumerable<object>).Cast<IProperty>();

            if (cast == null)
            {
                System.Diagnostics.Debugger.Launch();
            }
            
            return cast
                    .Select(x => x.Type.Unwrap())
                    .Where(x => !x.IsPrimitive && !x.IsValueType || x.IsEnum)
                    .Distinct()
                    .ToArray();
        }

@NeVeSpl
Copy link
Owner

NeVeSpl commented Jun 15, 2024

Scriban is a typeless language and its built-in functions do not care about returning the correct type.

As an alternative to what you already got, you could make a custom function to select public properties that will return IEnumerable<IProperty>, that way you should be able to use the original/typed version of GetClassTypes(IEnumerable<IProperty> publicProperties).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants