A Typescript object with unspecified properties that are all filled with values

Is it possible to create a type that accepts an object with any properties, but requires at least one (unknown) property to be defined?

// attempting to implement this

type CustomType = {
  [key: string]: any
}

const customObj: CustomType = {} // this should trigger an error
const newCustomObj: CustomType = { something: "thing" } // this should be valid

Answer №1

Thanks to the input from @Fahd Lihidheb, this solution is what comes to mind:

type NotEmpty<T> = keyof T extends never ? never : T

function createTest<T extends {[key: string]: any}>(test: NotEmpty<T>): T {
  return test
}

const obj = createTest({})                            // error
const anotherObj = createTest({ something: "thing" }) // works

Just defining a type may not be enough. Using a factory method allows us to dynamically infer the type of T and verify if any keys are present.

Answer №2

While occupied with another task, I stumbled across a potential solution.

type NonEmptyObj<T extends Record<string, unknown>> = T extends Record<string, never> ? never : T;

This method relies on Record<string, never> to define an empty object and checks if T does not extend an empty object.

If implemented, it would appear like this:

function someFunction<T extends Record<string, unknown>>(foo: NonEmptyObject<T>) { ... }

Link to TS playground

Is this advisable? Probably not. The error message generated by this type check is not very helpful, and the potential application is quite limited.

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

Configuring ESLint, Prettier, and TypeScript in React Native: A Step-by-Step Guide

Could you provide guidance on setting up ESLint, Prettier, and TypeScript in React Native? I'm currently using absolute paths to specify components. Can you confirm if this setup is correct? tsconfig { "extends": "@tsconfig/react-n ...

Tips for Concealing and Bypassing Array String Elements in Angular 4/6 with Typescript or Html

Currently, I am working on a feature where clicking on a specific item in the list of branches should remove or hide that particular item and display it in another section as the selected branch. The swapping functionality is working fine, but the item sti ...

The type '(s: string) => string' cannot be assigned to type '<T>(t: T) => T'

I defined an interface in Typescript as shown below: interface ProductFieldMapping { name: string, mapping: (p: Product) => string | number, formatting: <T>(t: T) => T, } Also, I have a function that generates a list of such fields like ...

Angular 11 is giving an error message stating that the 'async' pipe cannot be located

Struggling to fetch data using Angular 11 as an observable? Issues arise when using async or JSON pipe in a lazy loaded component/module, resulting in errors displayed in the console. The module: import { NgModule } from '@angular/core'; import ...

Is it possible to retain the expanded items in a Nested Tree even after refreshing or updating the page?

I am working with a nested tree data structure that can be found at the following link: https://stackblitz.com/edit/angular-ivy-wcv63x?file=src%2Fapp%2Fapp.component.ts My objective is to maintain the selected tree items in an expanded state even after a ...

Utilizing an array for substituting sections of a string: a guide

I have an array of values like ['123', '456', '789']. What is the best way to iterate over this array and update parts of a string that contain the text :id in sequence (e.g. users/:id/games/:id/server/:id)? Currently, I&apos ...

What is the best way to implement a selected option in AngularJS 2?

Trying to understand how to preselect an option when displayed, I attempted it with old JavaScript style code or another language. For example: <select> for (x = 0; x < elements.size; x++) { <option value="element.id" if (element.id == selecte ...

React-scripts is not recognizing tests that have the .tsx file extension

Currently in the process of converting my project to TypeScript, everything is almost working perfectly. The code builds without issues and renders correctly. The only hiccup I'm facing is with my tests. I've observed that when I change a test f ...

Utilize AWS CDK Step Function Task to incorporate a list of objects within the DynamoPutItem operation

I am currently facing a challenge with using the DynamoPutItem task to insert an entry that includes a list of objects as one of its attributes. I have searched online for examples of this but have not found any, leading me to question if it is even possib ...

Comparing Redux and MVC models in software architecture

A new project is on the horizon, and the Product Owner has suggested using Redux for state management. However, I am hesitant to embrace this suggestion as I fail to see the advantages compared to a model-based approach. For instance, instead of utilizin ...

How to send a dynamic URL parameter to a function in Next.js TypeScript without using implicit typing

When utilizing the useRouter function with a parameter of type string, the following error is encountered: Type 'string | string[] | undefined' is not assignable to type 'string'. Type 'undefined' is not assignable to type & ...

Tips for calculating the total of keyup elements in an Angular application

There are "N" inputs in a formgroup that need to be summed: <input (keyup)="sum($event)" type="text" name="estoque_variacao{{i}}" class="form-control" id="estoque_variacao{{i}}" formControlName="estoque_variacao"> This is the Typescript code: sum( ...

Executing custom AWS CDK resource to configure database following the creation of an RDS instance

After setting up an RDS instance and an EKS cluster using AWS CDK and Typescript, I need to find a way to trigger a Lambda function to set up database users for microservices on EKS. The Lambda function should run after the RDS instance is created but befo ...

Convert an object to nested JSON in Angular 5

I am struggling with using Angular 5 HttpClient to send a post request because I am having trouble casting an object to nested JSON. For instance, I have the following class: export class Team { members: Person[]; constructor(members: Person[]) ...

Issue potentially arising from TypeScript's type validation

Take a look at this code snippet: I defined a union type, but accidentally omitted one of the types from the type predicate. As a result, the function returned a value that was not a number, and no type error was detected during compilation: type Car = Sko ...

Dynamic React Gallery with Interactive Image Picker

Looking to develop a new photo management application as an alternative to Google Photos, with a focus on displaying and selecting images in a user-friendly way. Currently using the react-grid-gallery library for this purpose. Here is my current implement ...

Retrieve all objects of the selected value using Angular autocomplete when an option is selected

I am currently working with an autocomplete component. I am passing an array of objects and would like to retrieve all item information (option) when an option is selected, not just the field value (option.name). <form class="example-form"> ...

Endlessly streaming data is requested through HTTP GET requests

I am facing an issue with my code where it requests data endlessly. The service I have retrieves data in the form of an Array of Objects. My intention is to handle all the HTTP requests, mapping, and subscriptions within the service itself. This is because ...

Passing parameters in React classes is a crucial aspect of creating

Within a project I am currently working on, there is a const defined for the page header which takes in parameters and utilizes the information: interface UserProps { user?: { name: string, image: string }, loading?: boolean, error?: E ...

What is the best way to properly mock certain methods within a Jest class?

Imagine having a class structure like this: located at ./src/myClass.ts class myClass{ methodA(){ ... } methodB(){ ... } } Now, let's say I need to mock method A. To do this, I created a file ./src/mocks/myClass.ts class ...