What could be the reason for TypeScript allowing the injection of an invalid type?

I have the following objects and classes that demonstrate dependency injection:

abstract class Animal {
    speak(): void {};
}

class Dog implements Animal {
    speak(): void {
        console.log('Woof woof');
    }
}

class Cat implements Animal {
    speak(): void {
        console.log('Meow meow');
    }
}

class PetOwner {
    pet: Animal

    constructor({ pet = new Dog() }: { pet?: Animal } = {}) {
        this.pet = pet;
    }

    communicate(): void {
        this.pet.speak();
    }
}


const owner1 = new PetOwner();

owner1.communicate(); // Woof woof

const owner2 = new PetOwner({ pet: new Cat() });

owner2.communicate(); // Meow meow

The above scenario works well as expected.

However, there is a strange occurrence...

class Parrot {
    speak() {
        console.log('Should not be possible, but it is.')
    }
}

const owner3 = new PetOwner({ pet: new Parrot() });

owner3.communicate(); // Should not be possible, but it works.

Why does TypeScript allow passing in a Parrot object when both the pet attribute in the PetOwner class and the pet parameter in the constructor are specified as type Animal?

Answer №1

In the realm of TypeScript, a Car can be considered equivalent to a Person due to its ability to mimic human behavior (specifically through the age method that matches the correct signature). TypeScript pays no heed to whether you specifically declare this implementation or not.

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

Difficulty persisting when removing accents/diacritics from a string in Angular with IE 11

When attempting to utilize the String.normalize("NFD").replace(/[\u0300-\u036f]/g, "") method, I encountered an issue in IE11. ERROR TypeError: The object does not support the property or method "normalize" ...

Checking JavaScript files with TSLint

After spending many hours attempting to make this work, I still haven't had any success... I am wondering: How can I utilize TSLint for a .js file? The reason behind this is my effort to create the best possible IDE for developing numerous JavaScrip ...

Refining Generic Types in TypeScript

Why does the generic type not narrow after the type guard in typescript v4.4.4? Is there a way to resolve this issue? type Data = X | Y | Z type G<T extends Data> = { type: 'x' | 'y' data: T } type X = { name: string } type ...

Angular Group Formation Issue

I keep encountering the following error: formGroup expects a FormGroup instance. Please pass one in. This is how it looks in HTML: <mat-step [stepControl]="firstFormGroup"> <form [formGroup]="firstFormGroup"> And in my Typ ...

Using Typescript to remove an element from an array inside another array

I've encountered an issue while trying to remove a specific item from a nested array of items within another array. Below is the code snippet: removeFromOldFeatureGroup() { for( let i= this.featureGroups.length-1; i>=0; i--) { if( this.featureGr ...

Converting typescript path aliases into local file paths

Just dipping my toes into typescript and grappling with module resolution. The problem seems straightforward (or so I think), but there's something off about my tsconfig.json. If my folder structure looks like this: + release + definitions + ...

What is the process for establishing the default type for an Activity Entity in Microsoft Dynamics?

Currently in the process of restructuring a portion of script code associated with the Fax Activity Entity within Microsoft Dynamics. Within the script code, the following can be found: document.getElementById("regardingobjectid").setAttribute("defaulttyp ...

Troubleshooting issues with accessing the _id property using Typescript in an Angular application

Encountering an Angular error that states: src/app/components/employee/employee.component.html:67:92 - error TS2345: Argument of type 'string | undefined' is not assignable to parameter of type 'string'. Type 'undefined' is ...

Introduce a specialized hierarchical data structure known as a nested Record type, which progressively ref

In my system, the permissions are defined as an array of strings: const stringVals = [ 'create:user', 'update:user', 'delete:user', 'create:document', 'update:document', 'delete:document&ap ...

What can TypeScript do with high-level type functions?

Take a look at the following pseudo-code attempting to define a higher-order type function with a function-typed parameter M<?>: type HigherOrderTypeFn<T, M<?>> = T extends (...) ? M<T> : never; The syntax M<?> is not va ...

Tips for troubleshooting TypeScript Express application in Visual Studio Code

Recently, I attempted to troubleshoot the TypeScript Express App located at https://github.com/schul-cloud/node-notification-service/ using Visual Studio Code. Within the launch.json file, I included the following configuration: { "name": "notifi ...

The function getStaticPaths() will generate a 404 error, indicating that the page

I have encountered a persistent issue with the getStaticPaths() function throwing a 404 error. After investigating, I suspect that the problem may lie in the implementation of the getAllPostIds() function, which is supposed to generate an array of object ...

Issues with Typegoose and Mongoose Enums when utilizing an array of strings

One of my enums is defined as follows: export enum Careers { WEB_DEVELOPMENT = 'Web Development', MOBILE_DEVELOPMENT = 'Mobile Development', UI_UX = 'UI/UX' } This particular enum is used as a mongoose property like so: ...

Whenever the return condition is false, make sure to subscribe to the Angular CanActivate Guard

In my UserAccessGuard class, I have a method that captures the current path and compares it to the user's available paths. However, I am facing asynchronous problems because the condition inside the subscribe block causes my Hasaccess variable to rema ...

Although the cucumber tests indicate success, protractor fails to interact with the elements on the webpage

Recently, I delved into the realm of Protractor+Cucumber+Typescript and devised a sample framework utilizing Page Object Design along with a small script to execute some click actions. URL: My endeavor to click on the "Customer Login" button seems futile ...

Issues with manipulating state using TypeScript Discriminated Unions"Incompatibility with setState

Imagine having a unique type structure like the one shown below: export type IEntity = ({ entity: IReport setEntity: (report: IReport) => void } | { entity: ITest setEntity: (test: ITest) => void }); Both the entity and setEntity fun ...

What is the process for importing a map from an external JSON file?

I have a JSON file with the following configuration data: { "config1": { //this is like a map "a": [ "string1", "string2"], "b": [ "string1", "string2"] } } Previously, before transitioning to TypeScript, the code below worked: import ...

Is there a resource or extension available for identifying design flaws in Typescript code?

Currently, I am in the midst of an Angular project and am eager to identify any design flaws in my Typescript code. Are there any tools or extensions available that can help me pinpoint these design issues within my project? Any assistance would be greatl ...

Simulating an API endpoint using a spy service (using Jasmine)

I'm currently trying to simulate an API route within a spy service using Jasmine. Being relatively new to Angular, Typescript, and Jasmine, I find myself uncertain about where to place my code - whether it should go in the beforeEach block or in its ...

Ways to resolve: The JSX component does not contain any construction or call signatures

I've been grappling with a persistent issue regarding the creation of custom elements dynamically in React TypeScript. If you're curious, you can check out the question here. const generalButtons: MenuButton[] = [ { text: "New Cl ...