Functions returning generic arrays break type inferences

Hey guys,

 I ran into an issue with some typescript generics.  Everything worked fine in typescript, but the block editor wasn't happy.

 Here's my minimal reproducible example:

 Basically, if I have a generic function like tihs:
     * TODO: make an array of things
     * @param thing what to make an array of
    //% block
    export function arrayify<T>(thing: T): T[] {
        return [thing];

I can use it to create a variable just fine. But, when I try to use that variable outside the scope of declaration, it infers the type to be T and I get a type error saying it cannot find type T.

function doSomething () {
    return aThing
let aThing: T[] = []
aThing = custom.arrayify(0)

Where do you usually submit issues like this? Has anybody found a good way around this?


1 Like

Most issues go here:

But since your problem is related to the block editor, it might actually go somewhere else…

Generics aren’t supported in blocks currently - the existing array methods that are generic are heavily special cased our blocks compiler / fairly fragile. You can possibly get away with using any / any[] for the types to get something kind of working (but of course it won’t identify the types correctly / that is also a bit fragile as it stands)

Thanks. I was able to get it to work with any. What I was hoping to make was a jagged array of colors for a neopixel ring. Jagged arrays didn’t work out of the gate so I was going to make a function with a switch to effectively mimic a jagged array.

I wanted to have a helper block for making it easier to make an array of 24 colors when you only needed 2 colors to repeat 24 times. I figured I’d make them generic so they could be reused. I could also just explicitly make them number[]s and it would probably work.

I ended up just making a class to act like the jagged array and that got around the generics issue because there wasn’t a need for a global reference to each color array.

What I’m struggling with is what do I build to help my kids solve the problems they want to solve vs. what do I tell them isn’t possible so that they’ll work around it? :slight_smile:

Maybe this answers some of your questions with what is possible, as the Javascript is Static Typescript: