What is the best way to verify parameters in string interpolation when dealing with localization?

When working with typescript, the usual way to do string interpolation is like this:

const name = "Jack"
const message = `Hello ${name}`;

This method allows for type checking, ensuring that if "name" does not exist, a compilation error will be triggered. However, in my application, I have multiple languages which necessitates a different approach (currently using Mustache for string formatting, but open to alternatives):

// strings are sourced externally, such as from a JSON file:
strings = {
  "message": "Hello {{name}}"
}

const name = "Jack";
const message = Mustache.render(strings.message, { name });

While this solution works, I am seeking a way to implement static checks for used parameters (e.g., triggering a compilation error if the parameter name is missing in any of the language instances within strings.message). Is there a method to achieve this? I came across a library that parses SQL in a type-safe manner:

https://github.com/codemix/ts-sql

Could a similar approach be applied for handling string interpolation in multiple languages? Any advice or existing tools/libraries/practices available for this scenario?

Answer №1

The issue lies in the inability to type-check the string "Hello {{name}}" directly. In order for type checking to function properly, the name variable needs to be treated as a JavaScript identifier rather than just a basic substring. Therefore, it seems using Mustache may not be feasible in this scenario.

To address this, you'll need to utilize a web templating system that is TypeScript-compatible. One potential solution is utilizing ReactDOMServer with Express. An example can be found here. For your situation, the code snippet would resemble:

const strings = {
  message: ({ name: string }) => <>Hello {name}</>
};
// Render like this:
const App = () => {
  const Component = strings.message;
  return <Component name={name} />;
};

Maintaining type safety will necessitate refactoring everything within the strings source file (though it's likely all type-safe solutions will call for such modifications).

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

Combine Typescript files from a dependent module to aid in debugging within a Next.js application

Trying to debug a project written in Typescript using Next.js, but facing issues with bundling TS files from a local dependent common library. Only JS files are included, which is not sufficient for debugging. The goal is to bundle all TS files from the w ...

Exploring the capabilities of the VSCode Volar extension in a project utilizing Vue 2, Nuxt, Typescript, and the @nuxtjs composition-api

Trying to set up the Volar VSCode extension for a NuxtJS / Typescript project and facing two issues in .vue file templates. Followed the installation guide for Vue 2 and Typescript, and enabled Take Over mode. Solved some codebase issues with the extensio ...

undefined event typescript this reactjs

I have come across the following TypeScript-written component. The type definitions are from definitelytyped.org. I have bound the onWheel event to a function, but every time it is triggered, this becomes undefined. So, how can I access the referenced el ...

"Improve your Angular ngrx workflow by utilizing the sandbox pattern to steer clear of

Currently, I'm trying to determine whether my implementation of the ngrx and sandbox pattern is effective. Here's the issue I'm facing: getFiles(userId: number, companyId: number) { this.fileService.getFiles(userId, companyId).subscribe(re ...

Issue in Angular: Attempting to access properties of undefined (specifically 'CustomHeaderComponent')

I have encountered a persistent error message while working on a new component for my project. Despite double-checking the injection code and ensuring that the module and component export logic are correct, I am unable to pinpoint the issue. custom-header ...

Utilize the super type as a generic parameter in TypeScript for stronger assertions

The Query Within TypeScript, utilizing the keyword extends allows for asserting a generic parameter as a 'subtype' of another type. For example: // class Base {} // class Child extends Base {} // edited: class Base { a = 1 } class Child extends ...

Encountering a Typescript error when trying to invoke a redux action

I have created a redux action to show an alert message export const showAlertConfirm = (msg) => (dispatch) => { dispatch({ type: SHOW_ALERT_CONFIRM, payload: { title: msg.title, body: msg.body, ...

Tips for merging DTO (Data Transfer Object) with non-DTO objects

I'm currently working on a new endpoint and I need to validate only two parameters (limit and offset) with the dto. The third parameter is not supposed to be checked. My controller test code is not functioning as expected. When I try to use it, the e ...

What is the best way to reduce a day from a string in TypeScript?

I'm struggling to subtract one day from the variable endDate, which is currently a string. I attempted the following method: moment(this.endDate).subtract(1, 'day').format() Unfortunately, this approach did not yield the desired results. ...

Exploring the world of Angular's HttpClient Requests and Responses

As I delve into the world of signals, I find myself immersed in tutorials and articles on the topic. When it comes to calling an API endpoint using httpClient, I have come across two main approaches that caught my interest. Surprisingly, there isn't m ...

Having difficulty employing jest.mock with a TypeScript class

Following the guidelines outlined in the ES6 Class Mocks page of the Jest documentation, I attempted to test a method on a TypeScript class called Consumer. The Consumer class instantiates a Provider object and invokes methods on it, prompting me to mock t ...

Mongoose version 5.11.14 is causing TypeScript error TS2506 when attempting to utilize async iterators, requiring a '[Symbol.asyncIterator]()' to be present

I have decided to stop using @types/mongoose now that I've discovered that mongoose 5.11 already includes type information. However, when I attempt to run my code through tsc, I encounter TypeScript issues specifically with the following line: for aw ...

Utilizing the react i18 library for localization in react, with the unique approach of fetching JSON files through an

Is there a way to store all the translations for multiple languages in a single JSON file, save it to local storage, and then retrieve the translations at runtime? Currently, I have translations stored in separate files on the backend in the public folder, ...

Managing the rxjs from an Array of observables when the array has no elements

Looking for a more elegant solution to handle the case where an array of observables is empty in the following TypeScript function. I want the observable to complete when subscribe() is called without the need for an initial check. I've already imple ...

Module import in Ionic

I'm encountering an issue with Ionic, Angular, and TypeScript, and I'm feeling a bit lost... I'm trying to call an external function from my file but I keep getting the following error: "Uncaught (in promise): TypeError: undefined is not an ...

What is the best way to invoke a function in a React component from another component?

I am working with a component structure that includes the Input component. In this component, there is a function called validate that is triggered by the onChange event. Here is a snippet of the code: https://i.sstatic.net/WjCLy.png import React, {FC, us ...

Explain what the term "stop unwrapping" means

I am currently attempting to expose a template ref using defineExpose so that I can utilize that template ref in the useElementSize composable. However, according to the documentation, "(refs are automatically unwrapped just like on normal instances)". Thi ...

Steps to resolve the issue of being unable to destructure property temperatureData from 'undefined' or 'null' in a React application without using a class component

CODE: const { temperatureData } = state; return ( <> <div className="flex flex-row"> {temperatureData.map((item, i) => ( <div className="flex flex-auto rounded justify-center items-center te ...

What is the best way to parse JSON data with Typescript?

I am dealing with JSON data structured as follows: jsonList= [ {name:'chennai', code:'maa'} {name:'delhi', code:'del'} .... .... .... {name:'salem', code:'che'} {name:'bengaluru' ...

Ways to determine programmatically whether a function is asynchronous

My goal is to override (monkey patch) the it() function of the Jasmine framework and determine if a function passed as the second argument is of type async. I attempted using instanceof Promise since async functions return a promise, but it never evaluates ...