Code Works in Javascript But not Blocks

So to summarize the issue at hand, I created an essential custom block extension for an upcoming game. And the blocks are just fine.

Blocks

Screen Shot 2023-08-10 at 11.08.42 PM

Extension Code
//% weight=99 color="#FFB836" icon="\uf035"
//% block="Literals"
namespace literals {
    //% block="id $newid name $newname image $newimg"
    //% newimg.shadow=dialog_image_picker
    export function setPlayerData(newid: string, newname: string, newimg: Image): any {
        const objLiteral = {
            id: newid, 
            name: newname, 
            image: newimg 
        }
        return objLiteral
    }
    //% block="id $newid background image $newimg"
    //% newimg.shadow=dialog_image_picker
    export function setPlayerBackgroundData(newid: string, newimg: Image): any {
        const objLiteral = { 
            id: newid, 
            image: newimg 
        }
        return objLiteral
    }
}

I then implemented it into my code via JavaScript. Now in the JavaScript client, everything functions smoothly.

let PlayerList: any[] = [
    literals.setPlayerData("bon", "Bon", assets.image`myImage`)
]

An implementation example is this code sample:

let selectedPlayer = PlayerList.find(player => player.name === "Bon")

However when switching to the Blocks client, that’s when issues begin.

Issue

When switching to Blocks, the array type changes to number:

let PlayerList: number[] = [literals.setPlayerData("bon", "Bon", assets.image`myImage`)]

// Or if I move things around for the sake of aesthetics...

let PlayerList: number[] = [
    literals.setPlayerData("bon", "Bon", assets.image`myImage`)
]

Now this seemingly automatic change obviously causes a plethora of errors:

Any help is appreciated, my goal is to keep the code adjusted at an ‘any type array’.

There’s a simple fix for this: Don’t return the any type

Not only is it bad practice, it makes it very difficult for us to do type inference when compiling the blocks code. Looking at your code, there’s also no reason I see to use it. Being the any type will let people drag this block into any other block input, for example you can drag it into the blocks from the Sprites category:

image

Which is obviously an error.

Instead, define a type to return like this:

interface LiteralType {
    id: string;
    image: Image;
    name?: string;
}
3 Likes

This really helps, thank you!

Moral of the story: Never use any[] in blocks

1 Like