What is the reason behind the ability to reassign an incompatible function to another in TypeScript?

I discovered this question while using the following guide: https://basarat.gitbooks.io/typescript/content/docs/types/type-compatibility.html#types-of-arguments.

Here is an example snippet of code:

/** Type Heirarchy */
interface Point2D { x: number; y: number; }
interface Point3D { x: number; y: number; z: number; }

/** Two sample functions */
let iTakePoint2D = (point: Point2D) => { /* do something */ }
let iTakePoint3D = (point: Point3D) => { /* do something */ }

iTakePoint3D = iTakePoint2D; // Okay : Reasonable
iTakePoint2D = iTakePoint3D; // Okay : WHAT

It's clear that iTakePoint2D's signature is incompatible with iTakePoint3D. Running iTakePoint2D({ x: 100, y: 200 }) will result in a runtime error, as the program cannot access the value of point.z.

Answer №1

When it comes to TypeScript, function parameters have a special bivariant property, which can either be a blessing or a curse depending on how you look at it. While some may question why this is not flagged as an error by the type system, the reality is that enforcing contravariance (making parameters wider but not narrower than expected) would introduce more errors in common practices. It's a trade-off between correctness and convenience, as explained in the TypeScript Design Non-Goal #3.

The issue of parameter contravariance has been discussed extensively, with considerations for compiler performance being a significant factor in why strict enforcement is avoided. However, there are talks about introducing a compiler flag specifically targeting standalone functions to enforce contravariance, although the timeline for implementation remains uncertain.


Hopefully, this sheds some light on the topic for you. Good luck!

EDIT: Interestingly, the very document you referenced touches upon the implications of bivariance, showcasing both its benefits (seen in event handler code) and drawbacks (illustrated by your example). Perhaps clearer distinctions could have been made in explaining these nuances.

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 best way to sequentially invoke methods in Angular?

When initializing in the ngOnInit() method, I need to call several methods synchronously. However, all these methods involve asynchronous calls to an API. The challenge is that certain variables must be set before proceeding with the subsequent methods. Un ...

"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 ...

"The ion-label in Ionic2 is cutting off some of the text and not displaying it

I'm currently facing an issue with ion-label inside ion-item. The description is not properly displaying and instead, it shows dot-dot.. ..I need the entire text to be visible. Is there any solution available? <ion-card *ngFor="let product of prod ...

Found a minor syntax problem in an Angular service related to error handling declaration

As I was working on customizing the Angular tutorial to fit my needs, I found myself wanting to merge the two error handler methods showcased in the tutorial into one. I appreciate the functionality of both methods and believe combining them will be benefi ...

Typescript's Patch<T> type enforces strictness within the codebase

There have been instances where I needed to 'patch' an object T using Object.assign(). For instance, when propagating changes you might modify a stateful object that other code references (common in reactive programming like MobX or Vue). It&ap ...

Using Typescript for testing React components: successfully passing an array of objects as props

My current approach involves passing an array of objects to mock component data for testing: const mockPackage = { id: '1232-1234-12321-12321', name: 'Mock Package', price: 8.32, description: 'Mock description', glo ...

TypeScript combines strong typing for arrays into a unified array of objects

I developed a JavaScript function that can merge multiple arrays into an array of objects based on provided key names. Here’s an example: const mergeArraysToSeries = (arrs, keys) => { const merged = []; for (let dataIndex = 0; dataIndex < arrs ...

What strategies can be employed to improve generic inference skills?

Looking at the scenario provided below, how can we enhance code reusability in a manner similar to foobarA? interface F<T, U extends string> { t: T, f: (u: U) => void } declare const foo: <T, U extends string>(type: U) => F<T, U>; ...

Using JSON data in an ArrayBuffer with TypeScript

I am currently struggling with converting the received ArrayBuffer data from a server via Websocket into another format. Below is the WebSocket code snippet: let ws = new WebSocket('wss://api.example.com/websocket'); ws.binaryType = 'arrayb ...

Embedded Facebook SDK posts appearing only after performing a hard refresh

I tried to implement sharing facebook posts on my client's website following the instructions provided in the Facebook embedded post documentation. The website is built using the React NEXT.js framework. I added the SDK right after opening the body ...

How can I set up TypeScript warnings in Visual Studio Code to display as errors?

Take this scenario for instance async function a() { await null; } In VS Code, there is a minor warning about using await: 'await' has no effect on the type of this expression. ts(80007) Is there a way to elevate that warning to an error in b ...

How to efficiently mock the $window object in Angular unit tests

Attempting to unit test an angular custom service written in Typescript has been a challenge for me. The service is designed to read a global variable defined on the Window object and I have made it promise-based for potential future AJAX calls. Below is a ...

Facing an issue with the TypeScript error in the Tailwind-Styled-Component Npm package. Any suggestions on how to troub

module.styles.ts File import tw from "tailwind-styled-components"; export const Wrapper = tw.div` bg-green-500 `; export const Link = tw.a` text-blue-500 `; home.jsx File import React from "react"; import { Wrapper, Link } from &qu ...

Tips for enlarging the font size of a number as the number increases

Utilizing the react-countup library to animate counting up to a specific value. When a user clicks a button, the generated value is 9.57, and through react-counter, it visually increments from 1.00 to 9.57 over time. Here's the code snippet: const { ...

Simulating chained responses in Express using JEST

I am relatively new to using jest and typescript, currently working on creating a unit test for a controller function in jest import { Request, Response } from 'express'; const healthCheck = (_req: Request, _res: Response) => { const value ...

Customizing MUI V5 Variants

I'm having trouble customizing the variant options in MUIPaper, and I can't figure out what mistake I'm making. The available types for the component are: variant?: OverridableStringUnion<'elevation' | 'outlined', Pape ...

Angular: ChangeDetection not being triggered for asynchronous processes specifically in versions greater than or equal to Chrome 64

Currently, I'm utilizing the ResizeObserver in Angular to monitor the size of an element. observer = new window.ResizeObserver(entries => { ... someComponent.width = width; }); observer.observe(target); Check out this working example ...

There is no index signature that accepts a parameter of type 'string' in the type '{ [key: string]: AbstractControl; }'

I'm currently tackling a challenge in my Angular project where I am creating a custom validator for a reactive form. However, I've encountered an error within the custom validators function that I am constructing. Below you will find the relevan ...

Angular loop using an HTTP GET request is producing garbled information

Currently, I have a loop that includes an http GET request. This is the sample loop code: for (let index = 0; index < datas.length; index++) { let car = datas[index].smiles; console.log('or--> ' + car); this.subscr = this.CarServ ...

Utilizing TypeScript in a browser with a .NetCore WebApplication

After going through numerous articles, I have not been successful in finding a solution. My challenge lies with a .net core WebApplication that utilizes typescript code instead of javascript. Here are the specific requirements: I need to be able to debu ...