What methods are used in TypeScript to verify Omit during the compilation process?

I'm puzzled by the functionality of this code when employing the Omit utility type:

type Foo = {
    prop1: string;
    prop2: string;
}

const foo: Foo = {
    prop1: 'prop1',
    prop2: 'prop2'
}

console.log(foo) // {"prop1": "prop1", "prop2": "prop2"}

type Bar = Omit<Foo, 'prop2'> & {
    prop3: string;
}

const bar: Bar = {
    ...foo,
    prop3: 'prop3'
}

console.log(bar) // {"prop1": "prop1", "prop2": "prop2", "prop3": "prop3"}

On the other hand, there is an issue when trying to use Bar directly:

const qux: Bar = {
    prop1: "prop1",
    prop2: "prop2", // '{ prop1: string; prop2: string; prop3: string; }' is not assignable to type 'Bar'
    prop3: "prop3"
}

Answer №1

The reason for this occurrence lies in the concept of excess property checking, which specifically applies to properties within object literals under certain conditions. Excess properties are not a significant type safety concern; the compiler only alerts about them if it anticipates that they may be disregarded immediately. For example, defining

const x: {a: string} = {a: "", b: ""}
is problematic because the b property cannot be safely accessed. On the other hand, assigning
const y = {a: "", b: ""}; const x: {a: string} = y;
is acceptable as y retains the information about b</code even if <code>x does not.

In general, having extra properties is not an issue related to type safety. It is necessary for the compiler to permit these additional properties for interface extension compatibility. TypeScript's structural type system would be compromised without this flexibility. While TypeScript lacks "exact types" like Flow, there is an ongoing request for their implementation at microsoft/TypeScript#12936. Currently, TypeScript relies on structural subtyping where {a: string, b: string} can be assigned to {a: string}, along with excess property checking that issues warnings selectively in specific scenarios.


When initializing bar, you're spreading foo, an existing variable, thus bypassing excess property checking since it's not an object literal. This behavior aligns with the intention outlined in ms/TS#41237.

Conversely, the initialization of qux involves adding excess properties directly within an object literal, triggering a warning because there's no mechanism in place to remember that qux includes a prop2 property.

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

The Ion-item-option button requires two clicks to activate

Within my ion-list, I have sliding items that are dynamically created using a for loop. Interestingly, when clicking on an item to navigate to another page, everything works fine. However, upon sliding an item, a button is revealed but it requires two clic ...

Encountering a problem with lazy loading of module routing paths. Issue arises when attempting to navigate to http://localhost:4200

AppLazyLoadingMoudle import {NgModule} from '@angular/core'; import {RouterModule, Routes} from '@angular/router'; const ROUTES : Routes = [ /* ProductModule (defined in the feature module) is loaded lazily when navigating ...

Generating form groups programmaticallyORDynamically

I recently utilized angular-archwizard to implement a wizard step with *ngFor However, I encountered an issue on how to create a dynamic formGroup for each step. In the code below, I managed to create a single formGroup for all steps, but my goal is to ha ...

Struggling to get my React Typescript styled component slider to function within the component

Check out my demo here I created a simple react application using TypeScript and styled components. The main feature is a slider that adjusts the height of a red box. The red box is a styled component and I pass the height as a prop. Everything was fun ...

Typescript MUI Autocomplete: Can you specify the parameter type of the PaperComponents function?

If you use MUI's Autocomplete, there is a property called PaperCompomponent that allows you to pass your own react component. This property is a function with properties as a parameter, which can then be used to pass on to your custom component. In T ...

Using AngularJS with CDN: A beginner's guide

If I need to create an app using AngularJS with Cordova in Visual Studio, do I need anything else besides the Google CDN for AngularJS? <!doctype html> <html ng-app> <head> <title>My Angular App</title> <script s ...

Using act() in React/Jest/MSW causes errors when waiting for a response

As I delve into learning how to unit test with React, my focus has shifted towards using TypeScript. Unfortunately, the course I am taking does not cover most errors related to TypeScript. In my testing journey, I have set up a simple testing function with ...

The issue of Undefined TypeError arises when using Angular HttpInterceptor and injecting any service

Issue: I'm facing a problem where I am unable to inject any service into the constructor of my HttpInterceptors. Every service I try to inject results in the error: TypeError: Cannot set property 'authenticationService' of undefined Even ...

Exploring the world of TypeScript and JSON.stringify functions in JavaScript

In this simplified scenario: export class LoginComponent{ grant_type: string="password"; jsonPayload: string; Login(username, password){ this.jsonPayload = JSON.stringify({ username: username, password: password, grant_type: this.g ...

Leverage es6 classes along with mongoose in typescript to utilize loadClass functionality

I've been struggling with a problem and despite my exhaustive search on Google, I still haven't found a solution. My issue revolves around incorporating es6 classes with mongoose using the schema.loadClass(class) method. Unfortunately, when worki ...

Can a self-referential type truly exist?

There is a function that takes in a configuration object containing color definitions. For example: useColors({ colors: { RED: { hex: 0xff0000 }, GREEN: { hex: 0x00ff00 }, BLUE: { hex: 0x0000ff } }, doSomethingWithColor(getColor) { g ...

What distinguishes Angular directives as classes rather than functions?

When using Ng directives within HTML tags (view), they appear to resemble functions that are called upon rather than instances of a class. It almost feels like they could be static methods that can be invoked without an instance of a class. Comin ...

What is the best way to swap out the if else statement with a Ternary operator within a JavaScript function?

Is there a way to replace the if else statement in the function using a Ternary operator in JavaScript? private getProductName(productType: string): string { let productName = 'Product not found'; this.deal.packages.find(p => p.isSele ...

A custom Typescript type for immutable values within an object

I am struggling with finding the right data type for my function, where I need to work with static types. I have experimented with Type, interface, class, Record, and others, but none seem to fit perfectly. GEOLOCATIONS is a constant record that maps cou ...

Monitoring the current scroll position and updating other components on changes

Is there a way to easily monitor the scroll position of the browser and inform multiple components about it? For example, I would like to dynamically change the classes of different elements on the page as the user scrolls. In the past, with older version ...

How can I adjust the column width in OfficeGen?

Currently, I am utilizing officeGen for the purpose of generating word documents. <sup> let table = [ [ { val: "TT", fontFamily: "Times New Roman", }, { val: "Ten hang", ...

TypeScript test framework for testing API calls in VS Code extensions

My VS Code extension in TypeScript uses the Axios library for API calls. I have written tests using the Mocha framework, which are run locally and through Github Actions. Recently, I integrated code coverage reporting with `c8` and I am looking to enhanc ...

Adding TypeScript types to an array within a function parameter: A step-by-step guide

Having some trouble defining the array type: The code below is functioning perfectly: const messageCustomStyles: Array<keyof IAlertMessage> = [ 'font', 'margin', 'padding' ]; r ...

Using react-hook-form to easily update form data

While working on my project with react-hook-form for updating and creating details, I encountered a problem specifically in the update form. The values were not updating properly as expected. The issue seems to be within the file countryupdate.tsx. import ...

Find all Mondays occurring within a specified date range using Moment.js

I need to extract all Mondays within a specific date range. let start = moment(this.absence.FromDate); let end = moment(this.absence.ToDate); The user has the option to deactivate certain weekdays during this period by setting booleans. monday = true; t ...