What is the best approach to creating an array of complete objects from incomplete objects in TypeScript?

Unit tests are necessary for validation. Here is an example:

type X = 1 | 2 | 3;
type Y = 4 | 5 | 6;
type Obj = {
  x: X;
  y: Y;
};

I am trying to achieve something like this:

const getObjTemplate = (overrideProperties: Partial<Obj>): Obj => ({
  x: 1,
  y: 4,
  ...overrideProperties,
});

describe('Test suite', () => {
  const objs: Obj[] = [
    { x: 1 },
    { x: 2 },
    { x: 2 },
    { x: 3 },
  ].map(getObjTemplate);

  test('...', () => {
    // ...
  });
});

An error message stating

Type 'number' is not assignable to type 'X | undefined'
pops up in regards to property x because it seems incompatible with the Partial<Obj>. It could be that I am misusing Partial or assuming too much about Typescript's inferencing capabilities, but I expected it to deduce the type of x and ensure any added properties fit the same type.

How can I specify that overriding properties must match the original types?

You can experiment on the Typescript playground here.

Answer №1

The specific type of

[{ x: 1 }, { x: 2 }, { x: 2 }, { x: 3 }, ]
has not been clearly defined. Typescript is inferring it as {x: number}[], but you desire it to be inferred as Partial<Obj>[].

To achieve this, you can initialize an object.

const partials: Partial<Obj>[] = [{ x: 1 }, { x: 2 }, { x: 2 }, { x: 3 }, ]
const objs: Obj[] = partials.map(getObjTemplate)

If you wish to assert that the literal is readonly, you can do so using the following code:

const objs: Obj[] = ([{ x: 1 }, { x: 2 }, { x: 2 }, { x: 3 }, ] as const).map(getObjTemplate)

Answer №2

TypeScript is struggling to grasp the concept that { x: 1 } is not just a simple Obj, but rather a Partial<Obj>:

const objsList: Obj[] = [
    { x: 1 },
    { x: 2 },
    { x: 2 },
    { x: 3 },
  ].map(generateObjTemplate);

To resolve this issue, you can split it into two distinct steps:

const partialObjsList: Partial<Obj>[] = [
  { x: 1, },
  { x: 2 },
  { x: 2 },
  { x: 3 },
];

const finalObjsList: Obj[] = partialObjsList.map(generateObjTemplate);

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

Issue with variable not being populated by Observable

Although my observable is sending back the correct object, I am facing an issue where the data is not being stored against a local variable. import { Component, OnInit, OnDestroy } from '@angular/core'; import { LookupListsService } from '.. ...

The error message pops up when an Angular Library being utilized by another application encounters an issue: "Function calls are not supported in decorators but 'LoggerModule' was called"

I developed an Angular library with services to be utilized in various Angular applications. The functionality works smoothly without the --prod flag, indicating it works fine without Ahead-of-Time (AOT) compilation. However, when generating the library u ...

Using functions like .map in a TypeScript model may not function properly

After retrieving data from a server, I created a TypeScript model to structure the incoming data as follows: export class DataModel{ public PageNo: number public showFromDate: string public showToDate: string public gradeFieldId: number } ...

Using Ionic to send HTTP requests with authentication headers

I'm encountering an issue with Ionic where it insists on sending a pre-fetch request to the server without a JWT token, causing the app to crash. Additionally, I need a way to capture non-200 responses from the server as it frequently returns errors l ...

Retrieve the values of a dynamic JSON object and convert them into a comma-separated string using Typescript

I recently encountered a dynamic JSON object: { "SMSPhone": [ "SMS Phone Number is not valid" ], "VoicePhone": [ "Voice Phone Number is not valid" ] } My goal is to extract the va ...

Sequelize: Issue with duplicate $ in JSON_EXTRACT function

Can anyone help me with an issue I'm facing when using double dollar in a query with JSON_EXTRACT? Here is my query: const user = await UserModel.findOne({ where: where(fn('JSON_EXTRACT', col('config'), '$.type'), ty ...

Can discriminated unions solely be utilized with literal types?

When looking at the code snippet below, I encountered an issue with discriminating the union type using the typeof operator. function f(arg: { status: number; one: boolean } | { status: string; two: boolean }) { if (typeof arg.status === "number&q ...

The binding element 'string' is automatically assigned an 'any' type

Here is the code I am working with: function Child( { name: string } ) { return ( <div> {name ? ( <h3> The <code>name</code> in the query string is &quot;{name} &quot; </h3& ...

Unlocking $refs with the Composition API in Vue3 - A step-by-step guide

I am currently exploring how to access $refs in Vue 3 using the Composition API. In my template, I have two child components and I specifically need to obtain a reference to one of them: <template> <comp-foo /> <comp-bar ref="ta ...

I'm unable to import correctly using the --compiler option

Having an issue here. I'm trying to bring in the typescript compiler. I used this command: bit import bit.envs/compilers/typescript --compiler Unfortunately, it didn't work. This is the error message: bit import [ids...] import components in ...

Assigning a value to an angular object

In my current project with Angular 16, I am executing a query on the database and assigning the returned number to a document number. Data Model export class Document { doc_data: string =""; doc_for: string=""; doc_number: number = 0; doc_ ...

How can one access DOM elements (getting and setting values) that are nested within an *ngFor loop?

How can I access the <span> and <select> elements in my code template shown below? <div *ngFor="---"> <div> <span></span> <select> <option></option> <option></option> ...

Exploring Typescript code through a practical example with reference to Uniswap's implementation

On the Uniswap website, I came across some code on the Swap page that caught my attention. You can find the code snippet in question at line 115 of the Uniswap GitHub repository. const { trade: { state: tradeState, trade }, allowedSlippage, cur ...

The BehaviorSubject will consistently emit identical values to each subscription

I am currently facing an issue with the BehaviorSubject where it emits a value for every subscription. This means that if I have, for example, 2 subscriptions to this.projectService.projectState$ streams using methods like async or tap, the projectState$ e ...

Insert data into Typeorm even if it already exists

Currently, I am employing a node.js backend in conjunction with nest.js and typeorm for my database operations. My goal is to retrieve a JSON containing a list of objects that I intend to store in a mySQL database. This database undergoes daily updates, bu ...

Building a React Typescript service with axios functionality

When creating a service and calling it from the required functional component, there are two different approaches you can take. 1. export const userProfileService = { ResetPassword: async (userId: string) => { var response = await http.get ...

Guide on leveraging the `ConstructorParameter` tool with generic-friendly types

Attempting to extract the constructor parameter type from a class, but the class in question accepts a generic type value. Does anyone know how to achieve this? Encountered error: ConstructorParameters<typeof(DictionaryClass<contentType>)[0]; ...

Using TypeScript to Make SOAP Requests

I am attempting to execute a SOAP request using TypeScript, but I'm encountering an issue when compiling the code with "tsc myfile.ts". Here is the code snippet: import Soap from 'soap'; function soapClientServer(){ const url ...

Enhance your coding experience with code completion and autocomplete in Angular/Typescript using ATOM within

Is it possible to have Codecompletion / Autocomplete in Atom similar to Webstorm? Currently I am getting familiar with TypeScript and really enjoying it, but the lack of Codecompletion support for my HTML files in Atom is quite frustrating. Having this f ...

Hold off until the asynchronous function has completed - Ionic2

I am developing in Ionic2 and encountering an issue: Within my component, there is a method called drawPlayer that fetches data from a Firebase database. Here is the code for this method: drawPlayer(){ this.playerData.drawThePlayer().on('value&a ...