Mapped TypeScript type requiring scalar properties and allowing optional objects

I am in need of a TypeScript generic type that has the capability to alter another type so that all scalar properties (such as strings, numbers, booleans, etc.) remain mandatory, while object types become optional.

For instance, given the User type below, I would like name and age to be obligatory, but for address to be made optional.

type User = {
  name: string;
  age: number;
  address: {
    street: string;
    postcode: string;
  };
};

Answer №1

As I was formulating this query, the solution dawned on me. It's amazing how helpful StackOverflow can be!

type ScalarTypes = string | number | boolean | Date;
type OptionalObjects<T> = {
  [P in keyof T as T[P] extends ScalarTypes ? P : never]: T[P];
} & {
  [P in keyof T as T[P] extends ScalarTypes ? never : P]?: T[P];
};

// this example is acceptable
const partialUser: OptionalObjects<User> = {
  name: "Me",
  age: 12,
};

// this scenario is also valid
const fullUser: OptionalObjects<User> = {
  name: "Me",
  age: 12,
  address: {
    street: "My Street",
    postcode: "AB123",
  },
};

// @ts-expect-error this will throw an error since name and age are missing
const emptyUser: OptionalObjects<User> = {};

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

Exploring the world of ng2-translate for translating texts

For the translation of headings and texts in my Angular2 web application, I utilized ng2-translate. However, I am facing a dilemma when it comes to translating texts that are passed from a .ts file. For example, I can easily translate texts in an HTML fi ...

There seems to be a troublesome character in the Nuxt3 production server causing some issues

When submitting an HTML encoded text to the server, everything runs smoothly on the development environment. However, once it is deployed to a Netlify server, the same request triggers a 500 error and the server side logging middleware only recognizes a PO ...

Theme customization in Material UI includes the addition of a custom color. However, this custom color is missing from the control values in Story

Currently in my project, I am utilizing a stack that includes React 18, TypeScript, MUI 5, and Storybook 6.5. I have been attempting to incorporate custom colors into my MUI Theme and have them reflect in Storybook's dropdown options for the color p ...

Leveraging npm for the development of my TypeScript/Node.js project

I'm facing challenges working on a project written in TypeScript and running on Node. I am finding it difficult to write the npm script to get it up and running properly for development purposes. What I am attempting to achieve is: clear the /dist f ...

Typescript - Creating a Class with Constructor that Extends an Interface without Constructor

I am faced with an interface structured as follows: interface Person { id: number name: string } In my implementation class for this interface, I have the following code: class PersonClass implements Person { id: number = 123 name: string = &apo ...

Error in Angular: The use of decorators in this context is not allowed.ts(1206)

In my current project using Angular 17 and PrimeNG 17, I am implementing a theme switching feature. I have been following a tutorial from the Primeng documentation at this link: https://www.youtube.com/watch?v=5VOuUdDXRsE&embeds_referring_euri=https%3A ...

Build an object using a deeply nested JSON structure

I am working with a JSON object received from my server in Angular and I want to create a custom object based on this data. { "showsHall": [ { "movies": [ "5b428ceb9d5b8e4228d14225", "5b428d229d5b8e4 ...

Behavior of Shadow DOM role when using the <a> element without an href attribute

Recently, I started working with the shadow DOM and encountered a strange issue: In my Ionic Angular application, there is a text styled like a link in this form (simplified): <a href="${ifDefined(this.href)}">link</a> When testing ...

Syntax for nested arrow functions in TypeScript

const fetchAsyncData = (input: { value: string }): AppThunk => async (dispatch) => { try { const fetchedData = await getData({ input.value }); } catch (error) { console.log(error); } }; An error message is displayed stating "No value ...

Create an abstract method that will return the properties of the constructor

To establish an abstract class in typescript, we can name it Entity, which contains an abstract method called constructorProps() that returns the array of properties required to build the derived class. For instance, if Foo extends Entity and does not hav ...

Issue with Angular 8: click event is not triggering when using ngFor directive to iterate through arrays of objects

Update: The original post has been modified to omit implementation details and complexity. I am facing an issue with an ngFor loop that invokes a method on a service. The method returns an array which is then iterated over by the for loop. The click even ...

The primary origin of TypeScript is derived from the compiled JavaScript and its corresponding source map

Being new to sourcemaps and typescript, I am faced with a project that has been compiled into a single javascript file from multiple typescript files. The files available to me are: lib.js (the compiled js code of the project) lib.js.map (the source map ...

Can anyone provide guidance on incorporating jQuery typing into an angular2 seed project?

I'm struggling to incorporate jQuery typings into my Angular2-seed project. Within my component, I am utilizing jQuery in the following manner: declare let $: any; export class LeafletComponent implements OnInit { ngOnInit(): void { th ...

SystemJS could not locate the root directory for RxJS

There seems to be an issue with SystemJS loading rxjs modules on Windows, as it throws a 404 Not Found error on the rxjs directory. This problem does not occur on OSX, and all modules are up to date. GET http://localhost:8080/node_modules/rxjs/ 404 (Not F ...

Problems encountered while building TypeScript on Azure's Hosted Agent

I'm currently working on an ASP.NET MVC application built in .Net5 that utilizes TypeScript files and includes NuGet package references for the following: <PackageReference Include="BuildBundlerMinifier" Version="3.2.449" /> ...

Dynamic TypeScript property that can only be assigned values from an array during runtime

I'm currently struggling with specifying allowed values for a property in TypeScript. Within my interface, I have statically typed the property like this: interface SomeInterface{ prop: "bell" | "edit" | "log-out" } However, I am looking for a w ...

What is the reason behind being able to assign unidentified properties to a literal object in TypeScript?

type ExpectedType = Array<{ name: number, gender?: string }> function go1(p: ExpectedType) { } function f() { const a = [{name: 1, age: 2}] go1(a) // no error shown go1([{name: 1, age: 2}]) // error displayed ...

Avoid circular dependencies in Angular 6 to ensure proper association between modules

When working with TypeScript, how should I handle the scenario where Cat has an owner: Person Person owns a pet: Cat Cat import {Person} from './person' export class Cat { owner: Person constructor(){ this.owner = new Pers ...

What is the most effective way to eliminate all values in an object key array except for one specific value?

Currently, I am developing an angular project and have encountered an object with the following structure: const obj = { fruits: ['apple', 'orange', 'None'], nation: ['usa'], city: ['New York', ' ...

Transferring data to a different module

I'm currently working on an Angular program where I am taking a user's input of a zip code and sending it to a function that then calls an API to convert it into latitude and longitude coordinates. Here is a snippet of the code: home.component.h ...