What is the reasoning behind TypeScript's decision to permit implicit downcasting in method parameters?

Consider the following example:

interface Vehicle{
    mass:number
}
interface InspectorClass{
    inspect(v:Vehicle):void
}


class Car implements Vehicle{
    mass = 2000
    wheels = 4
}
class Boat implements Vehicle{
    mass = 3000
    sails = 2
}


// with methods it silently fails:

class BoatInspector implements InspectorClass{
    inspect(v:Boat){ // interface contract silently violated!!!
        console.log(v.mass)
        console.log(v.sails)
    }
}

function runInspection(inspector:InspectorClass, vehicle:Vehicle){
    inspector.inspect(vehicle)
}

let myCar = new Car()
let myBoatInspector = new BoatInspector()
runInspection(myBoatInspector, myCar)


// with functions it checks properly:

type InspectorFunction = (v:Vehicle) => void

const inspectCar:InspectorFunction = function(v:Car){ // TypeScript complains as it should
    console.log(v.mass)
    console.log(v.wheels)
}

Experience TypeScript in action here

The specification of the interface declares that an Inspect method in an InspectorClass instance must be capable of inspecting any type of Vehicle. Why does TypeScript allow me to implement a class that only accepts Boats without raising an error? Is this behavior intentional or is there a way to enable strict checking for this scenario?

Answer №1

The provided link addresses the issue at hand. To resolve the code snippet you shared, it is advisable to include the --strictFunctionTypes flag and define your method signature as a function-valued-property signature:

interface InspectorClass{
    inspect: (v:Vehicle) => void
}

Access Playground link

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

Utilizing Regular Expressions as a Key for Object Mapping

Currently, I am facing a challenge in mapping objects with keys for easy retrieval. The issue arises when the key can either be a string or a RegExp. Assigning a string as a key is simple, but setting a regex as a key poses a problem. This is how I typica ...

What is the appropriate data type to specify for the useLoaderData() function, and in what

I'm currently delving into the deep #6 tutorial on NetNinja's react-router, but I'm attempting to implement it using TypeScript. My task involves fetching data from a JSON object, utilizing the useLoaderData() hook, and trying to properly ma ...

Encountering an issue with a custom hook causing an error stating "Attempting to access block-scoped variable 'X' before its declaration."

Currently, I am in the process of developing my initial custom hook. My confusion lies in the fact that an error is being displayed, even though the function is defined just a few lines above where it's invoked. Here is the relevant code snippet: f ...

Converting JSON data into an Angular object

I'm struggling to map the JSON data below to an Angular 7 object: [ { "id": "123456", "general": { "number": "123", "name": "my name 1", "description": "My description with <li> html tags ...

Having difficulty navigating to a different page in Angular 4

I'm currently attempting to transition from a home page (localhost.com) to another page (localhost.com/listing). Although the app compiles correctly, I encounter an issue where nothing changes when I try to navigate to the new page. My approach has m ...

Creating a TypeScript type that extracts specific properties from another type by utilizing an array of keys

In my TypeScript journey, I am working on crafting a type that can transform a tuple of keys from a given type into a new type with only those specific properties. After playing around with the code snippet below, this is what I've come up with: type ...

"Exploring the method to navigate through a nested Firebase collection linked to its parent collection

I have a forum application in development where users can ask questions and receive answers, each answer having its own 'like' feature. I am trying to access the 'likes' subcollection when viewing an answer, but I am unsure of how to do ...

There was an error in parsing the module: an unexpected token was encountered during the rendering

Recently, I've been working on configuring React with Typescript (for type checking), Babel for code transpilation, Jest for testing, ESLint for code checking, and a few other tools. You can find all the necessary files in the repository linked below. ...

FInding the inner value of a Vuetify chip

I have a Vue application that utilizes Vuetify chips to display information. I'm trying to log the value inside a specific chip when it is clicked, but I keep getting an undefined error when trying to access the array where the information comes from. ...

A guide on selecting the best UI container based on API data in React using TypeScript

I have been developing a control panel that showcases various videos and posts sourced from an API. One div displays video posts with thumbnails and text, while another shows text-based posts. Below is the code for both: <div className=""> &l ...

Enhancing Angular 4 classes with dependency injection techniques

Currently utilizing angular 4 and angular cli for my project development. I have created some classes that serve as the base for my components! However, as the constructors of these classes grow during development, I find myself in a phase where I need to ...

Is it possible for the binding model of Mat-Checkbox to be optional or null?

Greetings everyone! I am a newcomer to the world of Angular, where I have successfully created a dynamic list of checkboxes. However, I have encountered a challenge when trying to bind selected values from an API to these checkboxes. <div *ngFor="let b ...

Angular Form Validations - input values must not match the initial values

These are my current reactive form validations: ngOnInit(): void { this.userForm = this.formBuilder.group({ status: {checked: this.selectedUser.status == 1}, username: [this.selectedUser.username, [Validators.required, Validators.minLeng ...

Vuejs fails to properly transmit data

When I change the image in an image field, the new image data appears correctly before sending it to the back-end. However, after sending the data, the values are empty! Code Commented save_changes() { /* eslint-disable */ if (!this.validateForm) ...

What is the best way to verify the presence of a value in an SQL column?

I need to check if a value exists in a column. If the value already exists, I do not want to insert it into the table. However, if it does not exist, then I want to add new data. Unfortunately, my attempted solution hasn't been successful. You can fi ...

Error message: Conflicting type declarations across multiple files

I am facing a challenge with my TypeScript 'snippets' project. It seems that multiple .ts files contain type names (like Foo) that are the same. //file-a.ts type Foo = { } //file-b.ts type Foo = { } When attempting to compile, I encounter ...

Decide on the return type of a generic function depending on the parameters of the function

I have a series of TypeScript functions that are structured as follows: useCustomFunction = <T>(key: CustomType) : T => { // implementation details here } The parameter type is restricted to a specific set of strings: type CustomType = "apple ...

Tips for converting necessary constructor choices into discretionary ones after they have been designated by the MyClass.defaults(options) method

If I create a class called Base with a constructor that needs one object argument containing at least a version key, the Base class should also include a static method called .defaults() which can set defaults for any options on the new constructor it retu ...

Error: Angular2 RC5 | Router unable to find any matching routes

I am currently encountering an issue with my setup using Angular 2 - RC5 and router 3.0.0 RC1. Despite searching for a solution, I have not been able to find one that resolves the problem. Within my component structure, I have a "BasicContentComponent" whi ...

The error TS2304 occurs when the e2e tsconfig types cannot find the name 'browser'

I am facing challenges while setting up a sample angular project with a basic webdriverio end-to-end test, encountering some compilation errors in my e2e test. Setting up tsconfig The project is configured with the following key files: e2e / test / [e2e t ...