In Typescript, type errors in Object Spread Syntax are not causing any issues

In the following code snippets, the object spread syntax should generate a typescript error, but surprisingly no errors are being thrown.

It's important to note that I intentionally added a typo in the address property for this test.

Snippet A.1. - no error detected

interface TestType {
  company?: string;
  address?: string;
}

function testFunction(): TestType {
  const cond = true;
  const testDto = {
    ...(cond ? { company: '' } : {}),
    ...(cond ? { addressss: '' } : {}),
  };
  return testDto;
}

Snippet A.2. - no error detected

interface TestType {
  company?: string;
  address?: string;
}

function testFunction() {
  const cond = true;
  const testDto:TestType = {
    ...(cond ? { company: '' } : {}),
    ...(cond ? { addressss: '' } : {}),
  };
  return testDto;
}

Snippet A.3. - no error detected

interface TestType {
  company?: string;
  address?: string;
}

function testFunction() {
  const cond = true;
  const testDto= {
    ...(cond ? { company: '' } : {}),
    ...(cond ? { addressss: '' } : {}),
  };
  return testDto as TestType;
}

Snippet B.1. - error successfully caught

This snippet successfully throws a typescript error by removing the object spread syntax and placing the interface definition right after the constant name.

interface TestType {
  company?: string;
  address?: string;
}

function testFunction() {
  const cond = true;
  const testDto:TestType = {
    company: '',
    addressss: '',
  };
  return testDto;
}

Snippet B.2. - no error detected

Even without the object spread syntax, this snippet does not throw a typescript error, despite defining the interface in the function return type.

interface TestType {
  company?: string;
  address?: string;
}

function testFunction():TestType {
  const cond = true;
  const testDto = {
    company: '',
    addressss: '',
  };
  return testDto;
}

I verified my code on an online TypeScript editor to rule out any potential environment issues.

If anyone can shed light on what might be causing this anomaly, or provide a solution to detect misspellings when using object spread syntax, it would be greatly appreciated!

Many thanks in advance!

Answer №1

By using the ?: operator, you have declared company and address as optional in your TypeScript code.
Therefore, TypeScript is fine with your return object not having those properties defined.
If those properties were required, an error would be thrown:

interface TestType {
  company: string; // I removed the question mark
  address: string;
}

function testFunction(): TestType {
  const cond = true;
  const testDto = {
    ...(cond ? { company: '' } : {}),
    ...(cond ? { address: '' } : {}),
  };
  return testDto;
}

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

pressing the button again will yield a new outcome

I am looking to disable a button (material ui) when it is clicked for the second time by setting disabled={true}. Unfortunately, I have not been able to find any examples related to this specific scenario on StackOverflow. <Button onClick={this.s ...

How do I remove a specific object from my localStorage array in Angular?

Currently, I am storing and retrieving form values from localStorage. When displaying the data, I want to be able to remove a specific object that is clicked on. The issue is that my current code removes all the data instead of just the selected object. Be ...

Can the tiles in a grid-list be organized in a specific order?

I am facing an issue with a class named 'scenario' that has properties such as 'id', 'name', and 'number' among others. In the HTML, scenarios are displayed in this format: <mat-grid-list [cols]="breakpoint" r ...

Understanding how to handle prop types in a React application using Typescript

My current task involves using the react-google-maps library to integrate Google Maps API into my project. The documentation specifies a certain way to set up the maps component: const GoogleMapComponent: React.ComponentClass<{}> = compose( with ...

Guide on transforming a Unix timestamp into either "2000-01-01" or "2000-05-24 20:00:00" format, or the opposite way, using Deno

Just starting out with Deno and looking to convert a Unix timestamp such as 1646245390158 into either the format of 2000-01-01 or 2000-05-24 20:00:00, or vice versa. Any tips on how to achieve this? ...

What is the best way to create a sortable column that is based on a nested object within data.record?

I am utilizing jquery jtable to showcase some data in a table. I have been using the following code snippet for each field in the table to display the data and enable sorting: sorting: true, display: (data) => { return data.record.<whatever_value ...

Creating a singleton in TypeScriptWould you like to know how to declare a singleton in

My goal is to incorporate an already existing library into my TypeScript project. The library contains a singleton object that I want to declare and utilize. For example, within the xyz.js file, the following object is defined: var mxUtils = { /* som ...

`Is There a Solution When Compilation Fails?`

I keep encountering an issue when I run the command npm start. The problem seems to be originating from PancakeSwap Frontend and after several attempts, I am still unable to resolve it. Your assistance is greatly appreciated :) Below is a snippet of my Ap ...

Jest is having difficulty locating a module while working with Next.js, resulting in

I am encountering some difficulties trying to make jest work in my nextjs application. Whenever I use the script "jest", the execution fails and I get the following result: FAIL __tests__/index.test.tsx ● Test suite failed to run ...

Unit Testing AngularJS Configuration in TypeScript with Jasmine

I'm in the process of Unit Testing the configuration of a newly developed AngularJS component. Our application uses ui-router for handling routing. While we had no issues testing components written in plain Javascript, we are encountering difficulties ...

Switching from callback to function in TypeScript

Currently, I am utilizing the mongodb driver to establish a connection with mongo: public listUsers(filterSurname?:string):any { if (this.connected) { debug.log(this.db); var results; this.db.collection(' ...

TypeScript fails to acknowledge an exported enum

Currently utilizing TypeScript version 2.5.3 along with Angular 5. I have an enum defined in a separate file as follows: export enum eUserType { Driver = 1, Passenger = 2, User = 3 } To import and use it in another ts file, I do the following: i ...

What is the best way to store a gridster-item in the database when it is resized or changed using a static function

Following some resize and drag actions on my dashboard, I aim to store the updated size and position of my altered widget in my MongoDB database. Even though the gridster library offers the ability to respond to draggable and resizable events, these events ...

What is the method for assigning 'selective-input' to a form field in Angular?

I am using Angular and have a form input field that is meant to be filled with numbers only. Is there a way to prevent any characters other than numbers from being entered into the form? I want the form to behave as if only integer keys on the keyboard ar ...

Issue: "The argument provided must be a specific string, not a string or an array of strings."

Currently, I am tackling a Vue project that incorporates TypeScript and axios for handling API requests. While working on the Reset Password component, the resetPassword function within the auth.ts file appears as follows: resetPassword(password1: string, ...

What is the process of transforming an object type into a two-dimensional array using lodash?

In order to properly display multiple tables in my Angular project, I am looking to convert an object type into an array of different objects. The object I am working with is as follows: let myObject = { internalValue:{city:"Paris", country:"France", pin ...

Error occurs when attempting to test both boolean and number data within an ngIf statement

In the scenario where I am working with a template that includes a boolean called readOnly and an array known as arrayOfStuff: <span *ngIf="!readOnly && arrayOfStuff && arrayOfStuff.length">Hey</span> When running eitherng bui ...

When attempting to transfer data from the parent component to child components, the data is appearing as undefined in the display

I have been working on passing data from a parent component to child components, but I keep encountering an issue where the data is showing as undefined. Below is the code snippet: Parent Component In this section, I have declared the variable part_data ...

The absence of color gradations in the TypeScript definition of MUI5 createTheme is worth noting

Seeking to personalize my theme colors in MUI5 using TypeScript, I am utilizing the createTheme function. This function requires a palette entry in its argument object, which TypeScript specifies should be of type PaletteOptions: https://i.stack.imgur.com ...

Utilizing JSDoc for establishing an index signature on a class in ES6

When working with JSDoc, achieving the equivalent of Typescript's computed property names can be a challenge. In Typescript, you'd simply define it like this: class Test { [key: string]: whatever } This syntax allows you to access these comput ...