Violation of typescript object's structure

An error is generated by the code snippet below, which is expected:

const x = { x: 1 }
const y: typeof x = { x: 2, y: 3 }

// Error: Type '{ x: number; y: number; }' is not assignable to type '{ x: number; }'.

However, no error is produced by this code block:

const x = { x: 1 }
const y = { x: 2, z: 3 }

const z: typeof x = y

What issue exists in the second code snippet? Can type checks be enforced there?

Answer №1

The behavior is intentional, the a type is defined as {a: number}, meaning it must have at least the property a with a value of type number, but can also have other properties. TypeScript does not support closed object types where only specified properties are allowed. Therefore, including b in {a: number} is valid.

The error in the first case occurs due to an "excess property check," which flags additional properties when assigning an object literal directly to a type because they are often mistakes. However, this check is not triggered when assigning the object literal to an intermediary variable first.

Answer №2

TS utilizes structural typing over nominal typing, meaning that as long as an object has the required structure, it is considered valid.

As a result, it is possible to have additional properties on an object as long as they align with the existing ones in terms of name and type.

During object literal assignment, TS performs a strict check and does not permit extra properties.

This might seem inconsistent, but it is intentional design.

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

How can I properly prevent the use of a nested observable subscription within a loop?

Utilizing Angular2 along with Firebase through Angularfire2 to retrieve data from a Firebase Realtime Database, which essentially consists of a large JSON object. The current setup involves a polling system where polls are stored in a 'Polls' no ...

What exactly are Discriminating Unions in the realm of Function Types?

I am struggling to differentiate between members of a discriminated union made up of function types. Take a look at the following example: type _NumFunc = (n: number) => string; type _StrFunc = (s: string) => string; interface NumFunc extends _NumFun ...

Vue alert: Component resolution failed while attempting to create a global component

I am new to Vue Typescript and I have been encountering an issue while trying to create global components. I received a warning and the component did not load on the template. Here is how I attempted to create global components: App.vue import { createApp ...

What is the best way to utilize namespaces across multiple files in your program

I am currently working with TypeScript 1.6.2 and atom-typescript. In my project, I'm attempting to utilize namespaces across separate files: // Main.ts import * as _ from 'lodash' namespace Test { export var value = true } // Another.ts ...

Troubles with Declaration Merging in Angular 2 Implementation

I'm currently working on incorporating a custom RxJS operator into my project, following the steps outlined in this particular answer. Below are the relevant code snippets from my application: rxjs-extensions.ts import { Observable } from 'rxjs ...

Is there a way to determine when an animation finishes in Vue Nativescript?

Vue Nativescript does not support the v-on hook, even though I found a solution for VueJS. Check out the solution here Currently, I am applying a class to trigger an animation: Template <Image ref="Image" :class="{scaleOut: scaleOutIsActive}" ...

Angular 14: Enhance Your User Experience with Dynamic Angular Material Table Row Management

My inquiry: I have encountered an issue with the Angular material table. After installing and setting up my first table, I created a function to delete the last row. However, the table is not refreshing as expected. It only updates when I make a site chang ...

I find that ChangeDetectionStrategy.OnPush does not function as anticipated

Exploring the performance boost of ChangeDetectionStrategy.OnPush in Angular 2 (detailed here) has been my recent focus. However, I've encountered an interesting scenario. In my code, I have the parent component AppComponent: @Component({ selector ...

Angular encountering a null value within a pre-existing nested object

Upon receiving a fully populated object from my server to my angular service, everything appears correct in Postman and when I use JSON.stringify in the Angular component. However, I encounter an issue when trying to access nested objects within the view. ...

Uncertainty regarding the integration process of `create-react-app --template typescript` with typescript-eslint

After creating a react project using npx create-react-app my-app --template typescript, I was surprised to find that typescript-eslint was already enabled by default. https://i.sstatic.net/1uijf.png Upon inspecting the eslint config within the package.jso ...

The argument provided does not match the expected parameters

import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams } from 'ionic-angular'; import { EventDetail } from '../../models/event-detail/event-detail.interface'; import { AngularFireDatabase, Angu ...

Creating a custom type in Typescript using a function for testing purposes

I have been exploring ways to limit my search capabilities to specific criteria. Let's say I have a model and some data like the following: interface UserModel { _id: string; username: string; party: UserPartyModel; } interface UserParty ...

Is there a way to prevent the openlayers (4) map from redrawing when overflowing at the edges?

At the moment, my map keeps redrawing itself when I overflow the view, as shown in the image here: https://i.sstatic.net/xpyiP.png The countries displayed on the map are represented by simple geojson polygons. However, I want the map to stay fixed and n ...

An Unexpected ER_BAD_FIELD_ERROR in Loopback 4

I encountered an unusual error: Unhandled error in GET /managers: 500 Error: ER_BAD_FIELD_ERROR: Unknown column 'role_id' in 'field list' at Query.Sequence._packetToError (/Users/xxxx/node_modules/mysql/lib/protocol/se ...

Implementing a Typescript hook using useContext along with an uninitialized context object

I am currently attempting to develop a custom hook called useAuth in React 17 with TypeScript. While my solution is somewhat functioning, it requires the following syntax when utilizing the hook methods: const auth = useAuth(); // Do other stuff ...

Allowing HTML attributes in reusable components with Vue TSX: A guide on informing Typescript

Imagine I have a custom input component: import { defineComponent } from "@vue/runtime-core" export default defineComponent({ inheritAttrs: false, setup(props, { attrs }) { return () => ( <div> ...

Restrict the number of subscriptions allowed for an rxjs observable

Seeking a replacement for observable, subject, or event emitter that allows only one subscription at a time. The first subscriber should have priority to execute its subscribe function, with subsequent subscribers waiting their turn until the first unsubsc ...

Executing JavaScript code on ionic 2 platform

Recently, I developed a JavaScript algorithm and now I'm looking to implement it in my ionic 2 application. My preference is to avoid the hassle of converting the entire algorithm to typescript. While I managed to run javascript in the index.html page ...

Is there a way to render a component without having to render AppComponent constantly?

I am looking to display two components (AppComponent and UserComponent) without constantly displaying AppComponent. Here's how my code is structured: app.routing.module.ts const routes: Routes = [ { path: '', component: AppComponent ...

Passing a variable from the second child component to its parent using Angular

Need help with passing variables between two child components Parent Component: deposit.component.html <div> <app-new-or-update-deposit [(isOpenedModal)]="isOpenedModal"></app-new-or-update-deposit> </div> Deposit Component ...