How come Typescript allows me to generate intersection types that seem impossible?

Despite being unimplementable, the type definition below does not trigger any warnings from the compiler.

// No type error
type impossible = 0 & string[] & 'anything' 

An item cannot simultaneously be a number, a string[], and a string literal.

  1. What is the reason behind TypeScript allowing the creation of impossible types?
  2. Is there a practical scenario where defining unimplementable types serves a genuine purpose?

Answer №1

According to an explanation by Anders Hejlsberg on the topic:

Primitive types can be intersected (e.g. string & number), but it is not possible to actually create values of such types except for undefined. This limitation arises because these types can be generated lazily through instantiation of generic types, making it challenging to consistently detect and report errors relating to operations that involve creating these types.

In a comment made on July 3, 2015, he elaborated further:

An intersection type allows constituent types to serve as type parameters. For example,

declare function combine<T, U>(obj1: T, obj2: U): T & U;

This enhancement provides additional expressiveness, enabling better representation of existing JavaScript practices. However, due to the ability to instantiate type parameters with any type arguments, it is not feasible to pre-check the validity of an intersection type. Therefore, we must be prepared to intersect various types and handle situations where no values are valid (e.g. string & number). While some may argue that we should raise errors upon instantiation of such types, the deferred nature of type instantiation in a polymorphic system aims to prevent type proliferation and ensures error reporting remains manageable and deterministic.

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

"Modifying the form of an item by adjusting its variable, and rendering certain object properties as

let myObj = { a: { value: 1 }, b: { value: 2 } } myObj = { // How can I make the property b optional in myObj without specifying my own type? a: { value: 123 } } Is there a way to make the property myObj.b ...

Encountered an issue trying to access undefined properties while reading 'PP'

I am trying to showcase the data retrieved from my JSON file. Here is a glimpse of the information stored in the JSON => Within DTA > PP , I am specifically interested in displaying the variable NOMFAMILLE. An error message has caught my attentio ...

Tips for sending back a response after a request (post | get) is made:

In the service, there is a variable that verifies if the user is authorized: get IsAuthorized():any{ return this.apiService.SendComand("GetFirstKassir"); } The SendCommand method is used to send requests (either as a post or get request): ApiServi ...

What could be causing the Properties Array to come back as undefined?

When attempting to add an item to an array stored in the properties, I am encountering an error: "Cannot read properties of undefined (reading 'value')." Within the props, the following interfaces are defined: ILinkItemProps.ts export interface ...

What is the best way to make two buttons align next to each other in a stylish and elegant manner

Currently, I am diving into the world of glamorous, a React component styling module. My challenge lies in styling two buttons: Add and Clear. The goal is to have these buttons on the same row with the Clear button positioned on the left and the Add button ...

Error message: The class heritage events_1.EventEmitter is invalid and cannot be recognized

There seems to be a problem with the [email protected] npm dependency. I am attempting to incorporate mongodb into my Vue.js + Vite + Typescript application, but it crashes and fails to load due to an error originating from mongodb. It appears that th ...

Using Javascript to parse SOAP responses

Currently, I am working on a Meteor application that requires data consumption from both REST and SOAP APIs. The SOAP service is accessed using the soap package, which functions properly. However, I am facing challenges with the format of the returned data ...

Sending an ID from an array within a *ngFor loop to a different component in Angular: a step-by-step guide

I have a collection of items that I loop through using ngFor. My goal is to pass all its attributes to another component. I attempted to accomplish this with the following code: *ngFor='let item of postList [routerLink]="['/detailed-post&ap ...

The supabase signup function keeps showing me the message "Anonymous sign-ins are disabled." Can anyone help me understand why this is happening?

I'm currently in the process of setting up authentication in Next.js with supabase, but encountering an issue when attempting to execute the signUp function. The error message I'm seeing is: Anonymous sign-ins are disabled Below is the snippet o ...

An issue occurred with building deployments on Vercel due to a typing error

When attempting to deploy my build on Vercel, I encountered an error. The deployment works fine locally, but when trying to build it on vercel, the following error occurs: [![Type error: Type '(ref: HTMLDivElement | null) => HTMLDivElement | null&a ...

Using event.target to pass HTML form data to FormData is causing an error stating that the Argument of type 'EventTarget' cannot be assigned to a parameter of type 'HTMLFormElement'

Looking to extract data from a form and store it in FormData: const handleSubmit = (e: FormEvent<HTMLFormElement>) => { e.preventDefault(); const formData = new FormData(e.target as HTMLFormElement); const value = formData.get(' ...

Issues arise with transferring React component between different projects

My goal is to develop a React component that serves as a navigation bar. This particular component is intended to be imported from a separate file into my App.js. Currently, the component is designed to simply display a 'Hello world' paragraph, ...

Enforcing TypeScript restrictions on method chaining during object creation

Let's consider this unique sample class: class Unique { public one(): Pick<this, "two" | "three"> { return this; } public two(): Pick<this, "three"> { return this; } public three(): string { ...

Custom React components are not designed to handle multiple onClick events simultaneously

One of my custom button components looks like this: export const Button = ({ children, onClick, className, ...props }: IButton) { const [selected, setSelected] = React.useState('primary') const handleSelected = () => { setSele ...

Exploring the power of Angular 10 components

Angular version 10 has left me feeling bewildered. Let's explore a few scenarios: Scenario 1: If I create AComponent.ts/html/css without an A.module.ts, should I declare and export it in app.module.ts? Can another module 'B' use the 'A ...

Keys preset in TypeScript using keyof

I need a set of predefined keys, but users should not be restricted to only using those keys. type B = { a: string; b: number; } type T = keyof B | string; function someFunc(key: T) {} someFunc(); // key type is `T` In the scenario above, I am lo ...

Error in Typescript index: iterating over properties of a typed object

My scenario involves an interface that extends multiple other interfaces from an external library: interface LabeledProps extends TextProps, ComponentProps { id: string; count: number; ... } In a different section of the codebase, there is an ...

Develop a novel object framework by merging correlated data with identical keys

I am trying to organize the related data IOrderData by grouping them based on the productId and brandId. This will help create a new array of objects called IOrderTypeData, where the only difference between the objects is the delivery type. Each product id ...

Guide to dynamically resizing the Monaco editor component using react-monaco-editor

Currently, I am integrating the react-monaco-editor library into a react application for viewing documents. The code snippet below showcases how I have set specific dimensions for height and width: import MonacoEditor from 'react-monaco-editor'; ...

Can you explain the significance of using an exclamation mark after defining a variable in TypeScript?

As I delve into TypeScript in an effort to enhance my programming skills, I have encountered the use of exclamation marks when defining variables. An example of this can be seen in the following code snippet: protected _db!: CheckpointDB ...