Typescript validation for redundant property checks

Why am I encountering an error under the 'name' interface with an excess property when using an object literal? There is no error in the case of a class, why is this happening?

export interface Analyzer {
    run(matches: MatchData[]): string;
}

const literalObject: Analyzer = {
    run(mtatches: MatchData[]): string {
        return '';
    },
    name: 'asd', //error
}

export class WinsAnalysis implements Analyzer {
    name: string = 'asd'; //fine

    constructor(public team: string) {

    }

    run(matches: MatchData[]): string {
        let wins = 0;

        for (let match of matches) {
            if (match[1] === this.team && match[5] === MatchResult.HomeWin) {
                wins++;
            } else if (match[2] === this.team && match[5] === MatchResult.AwayWin) {
                wins++;
            }
        }

        return `${this.team} won ${wins} times`;
    }
}

Answer №1

The code snippet you provided threw an error that stated:

Type '{ run(mtatches: unknown[]): string; name: string; }' is not compatible with type 'Analyzer'. Object literal can only define properties that are known, and 'name' is not part of the 'Analyzer' type.ts(2322)

When you assign an object to a specific type (in this scenario, Analyzer), you are specifying that the object will have only the properties mentioned in the type.

An object literal must precisely match the structure of the interface it is being assigned to. In this instance, since the 'Analyzer' interface does not include the 'name' property, trying to set a value for 'name' in the object literal results in an error being thrown.

Conversely, when you create a class that implements the 'Analyzer' interface, the class can include extra properties or methods beyond what is defined in the interface. For example, the class 'WinsAnalysis' has a 'name' property without being declared in the Analyzer interface, which is why no error occurs.

An interface serves as a contract that objects must adhere to.

By having a class implement an interface, you ensure that the class encompasses all the properties and methods specified within the interface.

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

What is the syntax for using typeof with anonymous types in TypeScript?

After reading an article, I'm still trying to grasp the concept of using typeof in TypeScript for real-world applications. I understand it's related to anonymous types, but could someone provide a practical example of how it can be used? Appreci ...

I'm receiving an error message stating "mongoose.connect is not a function" while attempting to establish a connection with mongoose. Can you help me troub

I'm a beginner in Node.js and I'm currently working on creating a node/express/mongoose server app using TypeScript. Below is my app.ts file: // lib/app.ts import express from 'express'; import * as bodyParser from 'body-parser&a ...

"Encountered a problem while attempting to download the .xlsx file through http.get in an angular application interfacing

Attempting to download a .xlsx file using Angular 7 and web API in C#, encountering the following error: https://i.sstatic.net/7pwDl.png The code snippet from my service.ts is provided below: public exportExcelFile(matchedRows: string, reportInfoId: num ...

What is the best way to run tests on this method using Jest?

import { format, getDaysInMonth, getMonth, getYear, isValid, parse } from "date-fns"; export class DateService { public getDaysInMonth(month?: Date) { return getDaysInMonth(month || new Date()); } What is the best way to test this func ...

Creation of Card Component with React Material-UI

I am facing difficulties in setting up the design for the card below. The media content is not loading and I cannot see any image on the card. Unfortunately, I am unable to share the original image due to company policies, so I have used a dummy image for ...

Searching for client using mqtt.js in Angular2 with Typescript yields no results

I am facing a unique issue while trying to incorporate the mqtt.js library into Angular 2 using TypeScript. Below is my app.component.ts file: import { Component } from '@angular/core'; import * as mqtt from 'mqtt'; @Component({ sel ...

Error message: Unable to locate module without the '.js' extension at the end of the import file path

It seems like the solution is not difficult, just something obvious. I am working on a simple TypeScript project. There are no modules involved, only TypeScript for compilation. The TS files compile into JS files in the dist folder, which are then connect ...

Different Approaches for Handling User Interactions in Angular Instead of Using the Deferred (Anti-?)Pattern

In the process of developing a game using Angular, I have implemented the following mechanics: An Angular service checks the game state and prompts a necessary user interaction. A mediator service creates this prompt and sends it to the relevant Angular c ...

Tips for exporting and reusing third-party types in TypeScript

I am facing a challenge with my package, which relies on a 3rd party package API for most of its functions. How can I export the types from the 3rd party package API in my own package? For instance: React uses @types/react to define its types Let's ...

Fix a typing issue with TypeScript on a coding assistant

I'm struggling with typing a helper function. I need to replace null values in an object with empty strings while preserving the key-value relationships in typescript // from { name: string | undefined url: string | null | undefined icon: ...

I'm encountering an error when trying to use makeStyles

Something seems off with MUI. I was working on my project yesterday and makeStyles was functioning properly, but now it's suddenly stopped working. I'm encountering an error when calling it here: I suspect the issue lies in the import statement ...

What is the best way to transform this JSON data into an array of key-value pairs in JavaScript?

Dealing with nested JSON data can be challenging, especially when trying to extract key-value pairs efficiently. If anyone has suggestions on how to simplify this process and improve readability, please share your insights. The goal is to transform the ne ...

Managing updates with the spread syntax: Dealing with undefined or null properties

Let's take a look at this example method: GetCustomerWithPoints(customerId: number): Customer { const customer = this.customerService.getCustomer(customerId); const points = this.pointService.getPointsForCustomer(customerId); return {...custo ...

Mapping an array of objects using dynamically generated column names

If I have an array of objects containing country, state, city data, how can I utilize the .map method to retrieve unique countries, states, or cities based on specific criteria? How would I create a method that accepts a column name and maps it to return ...

Using :global() and custom data attributes to apply styles to dynamically added classes

Currently, I am working on creating a typing game that is reminiscent of monkeytype.com. In this game, every letter is linked to classes that change dynamically from an empty string to either 'correct' or 'incorrect', depending on wheth ...

Exploring TypeScript: Navigating the static methods within a generic class

I am trying to work with an abstract class in TypeScript, which includes an enum and a method: export enum SingularPluralForm { SINGULAR, PLURAL }; export abstract class Dog { // ... } Now, I have created a subclass that extends the abstract cla ...

In Typescript, it is not possible to assign the type 'any' to a string, but I am attempting to assign a value that is

I'm new to TypeScript and currently learning about how types function in this language. Additionally, I'm utilizing MaterialUI for this particular project. The issue I'm encountering involves attempting to assign an any value to a variable ...

Mocked observables are returned when testing an Angular service that includes parameters

I'm currently exploring various types of unit testing and find myself struggling with a test for a service once again. Here is the function in my service that I need to test: Just to clarify: this.setParams returns an object like {name: 'Test&ap ...

What is the best way to hide the button when a user is viewing their own profile in an Angular application?

Each user has their own profile on the platform. A unique feature allows users to send messages by clicking a button when viewing other profiles. However, an issue arises where this messaging button also appears on a user's own profile. Is there a way ...

specifying a specific type in a declaration

In this scenario, my goal is to distinguish between different types when declaring a new type: type Schedule = { flag_active : boolean, } type Channel = { flag_archived : boolean } type CreateChangeLog = { from : null, to : Schedule | Channel } ty ...