Skip to content

Instantly share code, notes, and snippets.

@hazzard993
Created April 11, 2019 06:58
Show Gist options
  • Save hazzard993/bbd263c0a50a3e4acc9f06e49c466d3a to your computer and use it in GitHub Desktop.
Save hazzard993/bbd263c0a50a3e4acc9f06e49c466d3a to your computer and use it in GitHub Desktop.

Image Registry

LÖVE 2D can load images.

love.graphics.newImage("img/Player.png");

What is stopping you in TypeScript? The ImageRegistry.

This is a re-declarable interface that can be used to keep track of the image paths your program will use.

To opt-out of this system, add "ts-love/no-image-registry" to your tsconfig's types.

{
    "compilerOptions": {
        "types": [
            "ts-love",
            "ts-love/no-image-registry"
        ]
    }
}

However if you're interested in using this, you'll have the benefits of...

  • Image path autocompletion. Only available paths will be shown.
  • TypeScript will make sure only the image paths you deem valid will be used. Case sensitive, no spelling mistakes and nothing else.
  • More consistency.
  • No extra generated code.

To use it, re-declare ImageRegistry somewhere, maybe in an ImageRegistry.d.ts file.

interface ImageRegistry {
    "img/Player.png": any;
}

This interface can also be extended to provide metadata about the images too. This metadata will need to be manually checked with image updates.

interface ImageRegistry {
    "img/Player.png": { width: 100, height: 200 };
}

const p = love.graphics.newImage("img/Player.png");

function convertToIcon(image: Image<{
    width: 100,
    height: 100
}) {
    ...
}

// Fails. A 100x100 image is expected here.
convertToIcon(p);

If you're good with your typings, you can make TypeScript deem if an image is usable before the program even runs with no overhead code.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment