Implement an interface with a specific number of properties in TypeScript

I am attempting to create a custom type that defines an object with a specific number of key-value pairs, where both the key and value are required to be numbers. Here is what I envision:

type MatchResult = {
  [key: number]: number;
  [key: number]: number;
}

This particular type is meant to represent the result of a match between two teams, with the team ID as the key and the number of goals scored as the value (a practical application of this type).

However, there is an issue in the example above - it's not valid to have multiple index types defined.

Answer №1

If you're unsure of the keys in advance, they can be any number, allowing for a dynamic setup:

type MatchResult = {
 [key: number]: number
}

However, if you know the keys beforehand, you can specify them explicitly like so:

type MatchResult = {
 111: number,
 222: number
}

This enables accessing values using a[111], but not with undefined keys like a[232] assuming a is of type MatchResult.

Creating a type with exactly 2 integer keys may not be achievable in TypeScript as it would require contextual tracking of each object with type MatchResult.

A more practical approach would be defining a specific type, such as:

type TeamResult {
 id: number;
 result: number;
}

type MatchResult {
 host: TeamResult;
 guest: TeamResult;
}

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

A guide on crafting a type definition for the action parameter in the React useReducer hook with Typescript

In this scenario, let's consider the definition of userReducer as follows: function userReducer(state: string, action: UserAction): string { switch (action.type) { case "LOGIN": return action.username; case "LOGOUT": return ""; ...

Verification for collaborative element

I am currently working on creating a shared component for file uploads that can be reused whenever necessary. Interestingly, when I include the file upload code in the same HTML as the form, the validation functions properly. However, if I extract it into ...

Is it possible to deactivate input elements within a TypeScript file?

Is it possible to disable an HTML input element using a condition specified in a TS file? ...

Does a <Navigate> exist in the react-router-dom library?

Within the parent component import LoginPage from "pages/admin"; export function Home() { return <LoginPage />; } Inside the child component import { useRouter } from "next/router"; export default function LoginPage() { co ...

TypeORM - Establishing dual Foreign Keys within a single table that point to the identical Primary Key

Currently, I am working with TypeORM 0.3.10 on a project that uses Postgres. One issue I encountered is while trying to generate and execute a Migration using ts-node-commonjs. The problem arises when two Foreign Keys within the same table are referencing ...

What are the benefits of using one state in React with useState compared to having multiple states?

Is it more beneficial to optimize and enhance code readability in React using Hooks and Functional components by utilizing a single setState hook or having multiple hooks per component? To further elaborate, let's consider the following: When workin ...

Can we set a specific length for an array passed in as a prop?

Can we use Typescript to specify the exact length of an array coming from props? Consider the following array of objects: const sampleArray = [ { key: '1', label: 'Label 1', value: 9 }, { key: '2', label: 'Label 2&ap ...

The retrieval of cookies from the Response object is not possible with Typescript

While working on my google chrome extension, I implemented a post call that looks like this: public someapiCall(username: string, password: string) { var url = 'http://test.someTestServer.com/api/user/someApiCall'; let headers = new Hea ...

showcasing products from database with the help of Angular 12

Here are the files related to the item: Item file And here is the component file: Component file Lastly, this is the data service file: Data Service file However, issues arise when testing the code with console log statements as it indicates that the ...

When working with TypeScript in Node, the module ""http"" does not have a default export available

const httpModule = require('http'); httpModule.createServer((req, res) => { res.end('Hello World'); }).listen(3000, () => console.log('Server is running on port 3000')); I've installed @types/node but ...

Numerous toggle classes available

Having the following HTML inside a <span> element: <span (click)="openLeft()"></span> A method in a @Component sets a boolean variable like so: private isOpen: boolean; openLeft() { this.isOpen = !this.isOpen; } To toggle classes ...

Issue with ReactJS Typescript: Cannot assign type 'number' to type '0, 8, 16, 24, 32, 40, or undefined'

I am looking to implement a grid from material-ui in react using typescript. You can view the live demo here. I have made adjustments to the example to make it work with typescript. Here is how my demo.jsx file looks like: import { withStyles } from &apo ...

How do I disable split panel on Ionic 2 login page exclusively?

I have successfully implemented the split-pane feature in my app.html file. However, I am facing an issue where the split pane is being applied to every page such as login and SignUp. Can someone please guide me on how to restrict the split pane function ...

Error: The type 'boolean | (() => void)' cannot be assigned to type 'MouseEventHandler<HTMLButtonElement> | undefined'

Playing audio in a NextJS app while writing code in TypeScript has been an interesting challenge. The onClick() function performs well in the development environment, triggered by npm run dev. <button onClick ={toggle}> {playing ? "Pause" : ...

React: Content has not been refreshed

MarketEvent.tsx module is a centralized controller: import * as React from 'react'; import EventList from './EventList'; import FullReduce from './FullReduce'; import './MarketEvent.less' export default class Mark ...

What is the correct method for importing React in TypeScript (.tsx) to ensure optimal integration?

Within our TSX/React web application, we employ two distinct import styles for the react module: import * as React from "react"; as well as import React from "react" As far as I know, both methods function without any noticeable differences. Is there a ...

Is it better to convert fields extracted from a JSON string to Date objects or moment.js instances when using Angular and moment.js together?

When working on editing a user profile, the API call returns the following data structure: export class User { username: string; email: string; creationTime: Date; birthDate: Date; } For validating and manipulating the birthDate val ...

What is the safest method to convert a nested data structure into an immutable one while ensuring type safety when utilizing Immutable library?

When it comes to dealing with immutable data structures, Immutable provides the handy fromJs function. However, I've been facing issues trying to integrate it smoothly with Typescript. Here's what I've got: type SubData = { field1: strin ...

NestJS Logger: Issue setting logger types in main.ts

When attempting to specify logger types in main.ts as illustrated in the official documentation: const app = await NestFactory.create(ApplicationModule, { logger: ['error', 'warn'], }); await app.listen(3000); I am encountering an i ...

Exploring the process for transitioning between pages within Angular

I am working on an Angular project and I am looking to navigate to the registration page when the registration button is clicked. As a beginner, I attempted to link the registration page but encountered some issues. My goal is for the main page to disappea ...