Identifying misspelled names in shared resources textures during PIXI.js loading

Our game utilizes TypeScript, Pixi.js, VSCode, and ESLint.

We maintain a dictionary of image files as follows:

export function getAllImages(): {name: string, extension: string}[] {
    return [
        {name: 'tile_lumber', extension: '.svg'},
        {name: 'tile_brick', extension: '.svg'},
        ....
    ]
}

The images are loaded using the following method:

export function loadImages() {
    for(const img of getAllImages()) {
        PIXI.Loader.shared.add(img.name, getImagePath(img.name + img.extension), { crossOrigin: true })
    }

    PIXI.Loader.shared
        .on('progress', loadProgressHandler)
        .load(assetsFinishedLoading)
}

To retrieve an image for a player, we use the following code structure:

export function getBannerForPlayer(playerColor: PlayerColors): PIXI.Texture {
    switch(playerColor) {
        case PlayerColors.Bronze: return PIXI.Loader.shared.resources.banner_bronze.texture
        case PlayerColors.Silver: return PIXI.Loader.shared.resources.banner_silver.texture
        case PlayerColors.Gold: return PIXI.Loader.shared.resources.banner_goldf.texture
        ....
    }
}

An oversight in our code has led to a bug where banner_goldf should actually be banner_gold. Despite this error, the compiler does not flag it as incorrect. How can we ensure that such errors are caught during development?

Answer №1

Instead of simply listing definitions, you have the option to define a static variable for each image as follows:

export class ImageDefinition {
    name: string
    extension: string
    texture: PIXI.Texture | undefined
}

export class Images {
    static icon_player: ImageDefinition = {name: 'icon_player', extension: '.svg', texture: undefined }
}

To load the images, you can use the following code:

for(const img in Images) {
    const image: ImageDefinition = Images[img]
    PIXI.Loader.shared.add(image.name, getImagePath(image.name + image.extension), { crossOrigin: true })
}

Once the images are loaded, you can save the textures in your static variables like so:

export function assetsFinishedLoading() {
    for(const img in Images) {
        const image: ImageDefinition = Images[img]
        image.texture = PIXI.Loader.shared.resources[image.name].texture
    }
}

You can then access the textures using the following code:

const texture = Images.icon_player.texture

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"Choose one specific type in Typescript, there are no in-b

Need help returning an object as a fetch response with either the property "data" or "mes": { data: Data } | { mes: ErrMessage } Having trouble with TypeScript complaining about this object, let's call it props: if (prop.mes) return // Property &a ...

What is the best way to preserve an enumeration value in TypeScript?

Is there a way to save enumeration values in TypeScript? For instance: createArticle(name: string, clr: ??enumeration??) { return axios.post(`${environment.apiUrl}/cards`, { card: `${name}`, color: ??clr?? }, ... } PS: Conte ...

Discover the steps to initiate Firefox in Incognito Mode using NodeJS and Selenium!

Can anyone help me figure out how to launch Firefox in private mode using TypeScript? I have attempted the following code but it doesn't seem to work: static async LaunchFirefoxInPrivateMode():Promise<WebDriver> { //Setting up firefox capab ...

Retrieve a multitude of nested Records within the returnType that correlate with the number of arguments provided to the function

My goal is to dynamically define a deeply nested ReturnType for a function based on the number of arguments passed in the "rest" parameter. For example, if we have: getFormattedDates( dates: Date[], ...rest: string[] // ['AAA', 'BBB&apos ...

Utilizing the onscroll feature to trigger a function within a ScrollView

I am facing an issue with an animated view where I need to execute multiple events within the onScroll property. The current onScroll implementation is as follows: onScroll={ Animated.event( [{ nativeEvent: { conten ...

What is the best way to create unit tests for a React component using TypeScript?

I recently completed a small React project using TypeScript and decided to have it print numbers of li tags in the browser. During this process, I wanted to write unit tests that would test if the component created the HTML element . However, as someone ...

Encountering build errors in .xproj file when working with Type Script in ASP.Net Core

I recently started working on a new ASP.Net Core project and decided to integrate Angular 2 and Type Script by following a blog post tutorial. However, upon adding a Type Script file to my project, I encountered several build errors from the xproj file. h ...

Steps to activate zone-conscious bluebird assurances in Angular 8

In order to make all the promises in my Angular 8 project cancelable, I embarked on a quest to find the perfect library for the job. It was during this search that I stumbled upon bluebird.js, a promising candidate ;-) Following these guidelines on integr ...

Unlock the key to connecting the output of one observable to another in rxjs

I have a procedure for saving users in the database. These are the steps I take: 1) First, I validate the request. 2) Next, I hash the password. 3) Finally, I store the user details in the users collection along with the hashed password. Below is the ...

Difficulty fetching data on the frontend with Typescript, React, Vite, and Express

I'm currently working on an app utilizing Express in the backend and React in the frontend with typescript. This is also my first time using Vite to build the frontend. While my APIs are functioning correctly, I am facing difficulties fetching data on ...

Generate random entries from an object based on specific criteria and append them to a fresh object using Typescript

Experimenting with Ionic2 and Typescript has been my recent focus. I have an object that contains various meals, calorie counts, and meal types (such as vegan). This is how the object looks: [ { "id":14093, "name":"Proteinshake mit Wasser ...

Material-UI Slide component is encountering an issue where it is unable to access the style property of an undefined variable

Recently, I incorporated Material-UI Slide into my project and I'm curious about why the code functions correctly when written in this manner: {selectedItem && selectedItem.modal && selectedItem.modal.body ? ( selectedItem.modal.body.map((section ...

The power of Ionic 2 combined with the Web Audio API

I am currently developing an Ionic 2 application that requires access to the user's microphone. When working on a web platform, I would typically use the following code snippet to obtain microphone access. navigator.getUserMedia = (navigator['ge ...

How is it that TypeScript still expects a valid return from an overridden method, even when it cannot be reached?

After creating a generic RESTClient with some abstract functions, I encountered an issue where not all REST actions are implemented. In these cases, I wanted to throw an error. The problem arose when trying to override the TypeScript method to both return ...

Error code TS2749 is indicating that the identifier 'XXX' is being interpreted as a value instead of a type. Perhaps you intended to use 'typeof XXX' instead

I've encountered a strange issue while running my npm run dev command in my project built with Nuxt.js, which includes Vue.js components. While launching the application, I'm encountering errors related to TypeScript like TS2749: 'About&apos ...

How to pass an array as parameters in an Angular HTTP GET request to an API

Hey there! I'm relatively new to Angular and I've hit a roadblock. I need to send an array as parameters to a backend API, which specifically expects an array of strings. const params = new HttpParams(); const depKey = ['deploymentInprogre ...

Angular 2 - Beginner's guide to updating the header when navigating to a new route or page

SOLVED I am faced with a challenge involving multiple components in Angular2. Specifically, I have the following components: home component, default header, detail component, and detail header component. Each header has a unique layout. At the Home pa ...

What are the best practices for implementing jquery owlCarousel within an Angular 4 component?

I've included my 'carousel.js' file like this: $('#owl-carousel-1').owlCarousel({...}); and in carousel.component.html, I have: <div id="owl-carousel-1" class="owl-carousel owl-theme center-owl-nav home- carousel">....< ...

When running in VS Code, the terminal process is terminated with code ELIFECYCLE errno: 137. Closing VS Code fixes the problem

I've just started experiencing this problem in the last couple of days. Every time I try to build my Angular project, it keeps failing at a specific point with errors displayed below. The only workaround I've found is to close VS code and run t ...

Error in MatSort implementation - Argument cannot be assigned

I'm having trouble figuring out how to implement the Mat-Sort functionality from Angular Material. When I try to declare my variable dataSource, I get the following error: Argument of type 'Observable' is not assignable to parameter of type ...