What is the reason behind TypeScript's Omit function not validating the values of the properties that are omitted?

Context: (optional)

I was experimenting with ways to enhance the usability of the update(person: Person) function by allowing only a subset of properties to be updated. I considered two options:

  • Passing the id explicitly as the first argument to the update method, followed by Partial<Person> or Omit<Person, 'id'> as the second argument.
  • Keeping the update method's signature unchanged with only one input argument and ensuring that the object provided contains the id property.

Using Omit seemed like a suitable choice to me, although the keys to omit could be any string value.

Question:

Why doesn't TypeScript enforce the specific value of the keys when using Omit? Is there any valuable reason for this that I may be missing?

Take a look at the code below

export interface Person {
  id: string;
  age: number;
  name: string;
}

type UpdatePerson = Omit<Person, 'whatEver'>; // Why does 'whatEver' not trigger compiler errors?
type UpdatePerson2 = Pick<Person, 'id'> & Partial<Person>; // This correctly enforces a valid key
type UpdatePerson3 = Pick<Person, 'thisDoesNotCompile'> & Partial<Person>; // This line fails compilation as that property is not part of the interface

Currently, I am proceeding with update(person: UpdatePerson) and

type UpdatePerson = Pick<Person, 'id'> & Partial<Person>;
. This approach makes all properties optional while making the id mandatory.

Answer №1

In summary, this specific behavior was chosen to ensure maximum compatibility with existing DefinitelyTyped libraries, particularly in relation to the built-in Omit feature. By opting for a more lenient implementation of Omit, the risk of breaking existing libraries was minimized, even though it may result in slightly less compiler safety and autocomplete for future code.


The decision was influenced by discussions in microsoft/TypeScript#30825, including feedback from DanielRosenwasser:

It appears that the restricted Omit type would not satisfy a significant portion of DefinitelyTyped users. Hence, we opted for a more permissive approach which can be further constrained by individual requirements.

Additional insights were provided by co-author Ryan Cavanaugh:

There were multiple conflicting definitions of Omit within DefinitelyTyped, highlighting the challenge of satisfying all users. Despite attempts to determine a majority preference, only one definition avoids causing major disruptions.

This topic has surfaced frequently with related discussions on StackOverflow and GitHub. Meanwhile, concise strict alternatives can be easily implemented or obtained from libraries like type-zoo.

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

Troubleshooting problems when installing Angular and puppeteer

Recently, I started a fresh angular project with the goal of scraping data from a website and displaying it on my page. To achieve this, I thought of simply installing puppeteer via NPM after creating a new project. However, the compiler threw various erro ...

Difficulty with Ionic: unable to compile for android

I am currently working on an Ionic 3.4 project and trying to build it for Android testing. Following the installation of Android Studio, the Android SDK, and Java 8, I proceeded with the command: ionic cordova platform add android However, when I atte ...

How come ngOnChange is unable to detect changes in @Input elements when ngOnDetect is able to do so?

Check out this plunker Please note: In order to see the effect, you need to restart the app after entering the link. import {Component, OnInit, Input, OnChanges, DoCheck} from 'angular2/core' @Component({ selector: 'sub', templat ...

Both undefined and null are sometimes allowed as values in conditional types, even when they should not be

Do you think this code should trigger a compiler error? type Test<T extends number | string> = { v: T extends number ? true : false } const test: Test<1> = { v: undefined } Is there something I am overlooking? Appreciate your help! ...

Transform HTML elements within an *ngFor iteration based on a specific variable in Angular 4

In my current project using Angular 4, I am faced with the task of dynamically modifying HTML tags within an *ngFor loop based on a variable. Here is the code snippet that represents my approach: <mat-card-content *ngFor="let question of questionGrou ...

Creating a file logging system with log4js to capture Console logs

Is there a way to automatically log all console logs, including failed expectations and exceptions, to a file without using try and catch in JavaScript? In Java's LOG4j, the rootlogger feature does this by default. Is there a similar functionality ava ...

The Vue router fails to load when using create-vue@3

I've been experimenting with the Vue Router, but it's not giving me the expected outcome. While following the tutorial on https://router.vuejs.org/guide/, I found that if I use the CDN and place it in a standalone HTML file, it works fine. Howev ...

Encountered a hiccup with TSDX while trying to create a project using the react-with-storybook

My goal was to develop a UI components library using Storybook and React. This was my first time working with Storybook, so I followed the instructions provided in the documentation: I initiated the project by running npx tsdx create my-components in the ...

Issue during deployment: The type 'MiniCssExtractPlugin' cannot be assigned to the parameter type 'Plugin'

I'm working on deploying a Typescript / React project and have completed the necessary steps so far: Created a deployment branch Installed gh-pages for running the deployed application Added a deploy command as a script in the package.j ...

Automatically compile files while performing an npm install or update

I am looking for a way to automatically compile my TypeScript code into JavaScript when another project requires it. For example, when a project runs npm install or updates with my project as a dependency, I want a specific command to be executed after all ...

Contrast: Colon vs. Not Equal Sign (Typescript)

Introduction Hello everyone, I am new to Typescript and currently grappling with some fundamental concepts. When defining a parameter for a function, I typically specify the type like this: function example(test: string){...} However, as I delve deeper ...

Retrieving component attributes using jQuery or alternate event handlers

In my Angular2 component, I am facing an issue with using vis.js (or jQuery) click events. Despite successfully displaying my graph and catching click events, I encounter a problem where I lose access to my component's properties within the context of ...

Create an alternate name for a specific type of key within a nested record

There are three simple types available: const structureTypes = z.enum(["atom","molecule"]) const atomTypes = z.enum(["oxygen","hydrogen"]) const moleculeTypes = z.enum(["water","ammonia"]) The goal is to define a type for a cache where the keys correspond ...

JSON TypeScript compliant interface

My problem is quite common, but the solutions found on stackoverflow are not suitable for my specific case. I have a collection of objects that I need to manipulate, save, and load as json files. Here's an example of the interface: type jsonValue = s ...

Tips on deactivating a div when a checkbox is selected

I am currently working with a checkbox element in my code: <md-checkbox checked.bind="addEventCommand.allDay" change.delegate="allday()">All Day</md-checkbox> When the above checkbox is true, I want to disable the following ...

The issue with sorting in Angular 8 mat tables persists when dealing with multiple tables

As a newcomer to Angular, I am still learning and have encountered an issue with sorting in the mat table. I have multiple tables on one page, each separated by a mat tab. The problem is that sorting only works on the first table ("crane master list") in t ...

What could be causing the conditional div to malfunction in Angular?

There are three conditional div elements on a page, each meant to be displayed based on specific conditions. <div *ngIf="isAvailable=='true'"> <form> <div class="form-group"> <label for ...

I'm interested in creating a unique form validator in Angular that verifies if a string has a combination of letters and numbers. How can this be

Currently, I am developing a registration form within Angular that mandates users to create a password comprising of both letters and numbers. I am in need of embedding a personalized validator to uphold this regulation. What would be the most practical ap ...

Utilizing Redux in my ASP.NET MVC application with the help of RequireJS and TypeScript (Issue: Encountering a script error for "redux" dependency)

I'm currently working on integrating the Redux state library with my ASP.NET MVC application using TypeScript and RequireJS. For this simple application, I have set up a new ASP.NET MVC Project and stripped it down to only include the necessary node ...

Navigating through code in a monorepo using VSCode, Lerna, and Typescript

We maintain all of our Javascript related SDKs in a monorepo at Sentry. https://github.com/getsentry/sentry-javascript If you decide to clone this repository, make sure to properly set it up by running yarn install and then navigate to any file such as p ...