Signatures of indices

I'm struggling with defining types for the following code:

type Language = 'en' | 'nl';

interface CacheObject {
  [key: string | number | Language]: string;
}

const cache: CacheObject = {};

export const init = (dir: string): Promise<void> =>
  fsPromises.readdir(dir).then(files =>
    files
      .filter(files => files.endsWith('.json'))
      .forEach(async file => {
        cache[file.slice(0, -5)] = await import(`${dir}/${file}`);
      })
  );

export const translate = (lang: Language): any => (key: string) =>
  key.split('.').reduce((acc, val) => acc[val], cache[lang]);

The issues I'm facing are:

const cache: CacheObject
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'CacheObject'.
  No index signature with a parameter of type 'string' was found on type 'CacheObject'.
const cache: CacheObject
Element implicitly has an 'any' type because expression of type 'Language' can't be used to index type 'CacheObject'.
  Property 'en' does not exist on type 'CacheObject'.

Can anyone provide guidance on how to address these issues?

Answer №1

Don't overlook another error you're experiencing:

An index signature parameter type must be 'string' or 'number'
(It's possible that there is a bug in TypeScript where this error is hidden by other errors; during testing, there was a moment when the error disappeared but resurfaced after making minor changes to the code. Test the error)

If you intend to use Languages to incorporate specific elements into the type of your type, you must utilize a mapped type in conjunction with a type containing the index signature:

type CacheObject = {
  [key: string]: string;
  [key: number]: string;
} & Partial<Record<Language, string>>

Play

If you only included the index signatures to prevent the compiler from flagging issues with string indexing, but the object will only ever contain the specified languages, you might want to consider casting the indexing expression:

type CacheObject = Partial<Record<Language, string>>
cache[file.slice(0, -5) as Language] = await import(`${dir}/${file}`);

Play

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

Vite encounters issues when using PNPM because of import analysis on the `node_modules/.pnpm` package

When utilizing PNPM and Vite in a monorepo, I encountered a perplexing issue. The email addresses appearing like `<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c0b6a9b4a580f4eef4eef9">[email protected]</a>_@<a ...

How can I manually listen to Angular 2 events on a dependency injected instance?

Assume I am working with a component: @Component({selector: 'todo-cmp'}) class TodoCmp { @Input() model; @Output() complete = new EventEmitter(); // TypeScript supports initializing fields onCompletedButton() { this.complete.next(); / ...

Make sure a Typescript array contains a particular value

Currently, I am in the process of developing a dropdown-style component where the value and options are separate props. My goal is to incorporate Typescript to ensure that the value remains a valid option. Although I could perform this validation at runtim ...

The component 'Form' cannot be utilized in JSX because its return type, 'ReactNode', is not a valid JSX element

I'm facing an issue with my Next.js application written in TypeScript after updating react-bootstrap. After the update, I am encountering the following error when attempting to use the Form component from react-bootstrap: react-bootstrap: ^2.10.3 @typ ...

Encountering TS2304 error message while running TypeScript files indicates the inability to locate the name 'PropertyKey', in addition to another error - TS2339

I encountered an issue while attempting to execute a spec.ts file in the Jasmine Framework. After installing @types/core-js version 0.9.46 using the command npm i @types/core-js, I started receiving the following error messages: > ../../node_modules/ ...

Pass information captured from Mat Dialog up to the main component

Looking for a way to pass true/false boolean data from a dialog box into the parent component without just console logging the result? You want to store it in a variable in the parent component for further use. Any suggestions on how to achieve this? This ...

Encountering an error in a map operation does not hinder the subsequent map operation from being carried out

Within my angular application, I have implemented a Login method that performs the following tasks: login(username, password): Observable<User> { let data = new URLSearchParams(); data.append('username', username); data.append(' ...

The importance of displaying doughnut chart tooltips in Angular 5 console

Is there a way to consistently display tooltips for a doughnut chart? This code snippet might help: Chart.pluginService.register({ beforeRender: function(chart) { if (chart.config.options.showAllTooltips) { // create an array of tooltips // we ...

Creating a regular expression for validating phone numbers with a designated country code

Trying to create a regular expression for a specific country code and phone number format. const regexCountryCode = new RegExp('^\\+(48)[0-9]{9}$'); console.log( regexCountryCode.test(String(+48124223232)) ); My goal is to va ...

Having trouble inserting the current time into Firebase Firestore

Currently, I am looking to use the current time as an input in Firebase Firestore (timestamp). Initially, when using the code snippet below: today: number = Date.now(); everything appeared to function correctly. However, the time was only updated once, s ...

Nock does not capture the requests - Error: Failed to resolve address ENOTFOUND

Let me provide an overview of the structure in place. Jest is utilized for executing the testing process. Within my jest.config.json file, I incorporate the following line: "globalSetup": "<rootDir>/__tests__/setup.js", Inside setup.js, you will ...

The model fails to update when a blur event occurs

I am a beginner with Angular2 and I am currently working on creating a reactive form, specifically an interactive date input field. Here is my HTML code: <div class="date ui-input"> <input type="text" name="dateD" [ngModel]="model.date | dat ...

I am having trouble with updating an array in React useState. Every time I try to make changes, it keeps reverting back to the initial state. What could

My current task involves managing a state array called monthlyIncidents, which contains 12 numbers that need to be updated under certain conditions. I attempted to update the elements by copying the array, modifying the specific element, and then updating ...

Unlocking the Potential of Vue Class Components: Exploring Advanced Customization Options

Currently, I am working on a project using Vue 2 with Typescript. However, I am facing an issue where I cannot add options to the component. <script lang="ts"> import { Component, Vue } from "vue-property-decorator"; import HelloW ...

Error displaying messages from the console.log function within a TypeScript script

My node.js application runs smoothly with "npm run dev" and includes some typescript scripts/files. Nodemon is used to execute my code: This is an excerpt from my package.json file: { "scripts": { "start": "ts-node ./src/ind ...

AngularJS 2: Updating variable in parent component using Router

My current app.component looks like the following: import { Component, Input } from '@angular/core'; import {AuthTokenService} from './auth-token.service'; @Component({ selector: 'app-root', templateUrl: './app ...

The raw password value must be provided and cannot be left blank

I am currently learning Java Springboot and working on creating a todo app with React (TypeScript) and Springboot. As I attempt to signup, an error occurs stating "rawPassword cannot be null" from Springboot. My frontend is running on localhost:3000 and b ...

Navigate to a specific line in Vscode once a new document is opened

Currently, I am working on a project to create a VS Code extension that will allow me to navigate to a specific file:num. However, I have encountered a roadblock when it comes to moving the cursor to a particular line after opening the file. I could use so ...

Issue with locating module in Visual Studio 2015 when using Angular5 and TypeScript version TS2307

I'm currently attempting to integrate Angular in Visual Studio 2015 update 3, but encountering the following error: TS2307 cannot find module '../node_modules/@angular/core'. The error is shown in the image linked here. Can anyone help me fi ...

Is there a way to remove trigger characters in vscode api completion function?

I am developing a vscode extension that requires custom completion for json files. I would like to know if it is possible to hide the trigger character when using autocompletions. Let me explain further : Imagine the trigger character is '.' In ...