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

When trying to compile FirebaseUI with typescript and react-redux, users may encounter issues

I'm attempting to implement firebaseui for a login feature in react-redux using typescript. Here is the code snippet: import firebase from 'firebase'; import firebaseui from 'firebaseui'; import fire from '../FirebaseCreds&ap ...

What could be the reason for the absence of a TypeScript error in this situation?

Why is it that the code below (inside an arbitrary Class) does not show a TypeScript error in VSCode as expected? protected someMethod (someArg?: boolean) { this.doSomething(someArg) } protected doSomething (mustBePassedBoolean: boolean) { /* ... * ...

Handling errors in nested asynchronous functions in an express.js environment

I am currently developing a microservice that sends messages to users for phone number verification. My focus is on the part of the microservice where sending a message with the correct verification code will trigger the addition of the user's phone n ...

Receiving an error in Typescript when passing an object dynamically to a React component

Encountering a typescript error while attempting to pass dynamic values to a React component: Error message: Property 'title' does not exist on type 'string'.ts(2339) import { useTranslation } from "react-i18next"; import ...

Is there an issue with my approach to using TypeScript generics in classes?

class Some<AttributeType = { bar: string }> { foo(attrs: AttributeType) { if (attrs.bar) { console.log(attrs.bar) } } } Unable to run TypeScript code due to a specific error message: Property 'bar' d ...

Tips for avoiding the influence of the parent div's opacity on child divs within a Primeng Carousel

I'm struggling to find a solution to stop the "opacity" effect of the parent container from affecting the child containers. In my code, I want the opacity not to impact the buttons within the elements. I have tried using "radial-gradient" for multipl ...

The @output decorator in Angular5 enables communication between child and

Hello fellow learners, I am currently diving into the world of Angular and recently stumbled upon the @output decorators in angular. Despite my best efforts to research the topic, I find myself struggling to fully grasp this concept. Here's a snippet ...

Is time-based revalidation in NextJS factored into Vercel's build execution time?

Currently overseeing the staging environment of a substantial project comprising over 50 dynamic pages. These pages undergo time-based revalidation every 5 minutes on Vercel's complimentary tier. In addition, I am tasked with importing data for numer ...

After compiling the code, a mysterious TypeScript error pops up out of nowhere, despite no errors being

Currently, I am delving into the world of TypeScript and below you can find the code that I have been working on: const addNumbers = (a: number, b: number) => { return a + b } Before compiling the file using the command -> tsc index.ts, the ...

Hovering over the Chart.js tooltip does not display the labels as expected

How can I show the numberValue value as a label on hover over the bar chart? Despite trying various methods, nothing seems to appear when hovering over the bars. Below is the code snippet: getBarChart() { this.http.get(API).subscribe({ next: (d ...

Customizing default attribute prop types of HTML input element in Typescript React

I am currently working on creating a customized "Input" component where I want to extend the default HTML input attributes (props). My goal is to override the default 'size' attribute by utilizing Typescript's Omit within my own interface d ...

Problem with Ionic 2 checkboxes in segment controls

I encountered an issue with my screen layout. The problem arises when I select checkboxes from the first segment (Man Segment) and move to the second segment (Woman Segment) to choose other checkboxes. Upon returning to the first segment, all my previous ...

Tips for extracting a keyword or parameters from a URL

I'm in the process of creating my personal website and I am interested in extracting keywords or parameters from the URL. As an illustration, if I were to search for "Nike" on my website, the URL would transform into http://localhost:3000/searched/Nik ...

Is it feasible to connect to an output component without using EventEmitter?

When it comes to creating components, I've found it quite easy to use property binding for inputs with multiple options available like input(). However, when dealing with component outputs, it can be a bit complicated as there's only one option u ...

Tips for utilizing functions in an inline HTML translation pipe

My objective is to streamline the code by using the Angular translate pipe. Currently, I find myself using 8 curly brackets and repeating the word "translate" twice... there must be a more efficient approach. Here is my current code setup: <s ...

Establishing the types of object properties prior to performing a destructuring assignment

Consider a scenario where a function is utilized to return an object with property types that can be inferred or explicitly provided: const myFn = (arg: number) => { return { a: 1 + arg, b: 'b' + arg, c: (() => { ...

The autoimport feature is not supported by the Types Library

My latest project involves a unique library with only one export, an interface named IBasic. After publishing this library on npm and installing it in another project, I encountered an issue. When attempting to import IBasic using the auto-import feature ( ...

Exploring Angular 7: Leveraging class inheritance and the powerful httpClient

It has come to my attention that my services are quite repetitive. In an attempt to enhance them, I decided to delve into super classes and inheritance in Angular. However, I have been struggling with the constructor and super calls. Despite TypeScript com ...

Step-by-step guide on how to index timestamp type using Knex.js

I'm in the process of indexing the created_at and updated_at columns using knex js. However, when I try to use the index() function, I encounter the following error: Property 'index' does not exist on type 'void' await knex.sche ...

An error occurred: The property 'toUpperCase' cannot be read of an undefined Observable in an uncaught TypeError

Encountering an issue during the development of a mobile app using the ionic framework for a movie application. After finding an example on Github, I attempted to integrate certain functions and designs into my project. The problem arises with the 'S ...