Ways to mandate a field to only be of type object in TypeScript

I need to design a type that includes one mandatory property and allows for any additional properties. For instance, I require all objects to have an _id property of type string.

{_id: "123"} // This will meet the criteria
{a: 1} // This will not work as it lacks the _id field 
{_id:"sadad", a:1} // This is acceptable

What approach can I take in typescript to achieve this?

Answer №1

Clearly state that the type should include a key called _id, followed by any object key-value pair Record<string, unknown>

type ObjectType = { _id: string } & Record<string, unknown>;

const a: ObjectType = { _id: "123" }; // This will work
const b: ObjectType = { a: 1 }; // Error: Property '_id' is missing in type
const c: ObjectType = { _id: "sadad", a: 1 }; // This will work

P.S. Check out this reference for Record Key:

What is the Record type in typescript?

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

Universal Module Identifier

I'm trying to figure out how to add a namespace declaration to my JavaScript bundle. My typescript class is located in myclass.ts export class MyClass{ ... } I am using this class in other files as well export {MyClass} from "myclass" ... let a: M ...

Tips for distinguishing a mapped type using Pick from the original type when every property is optional

I am working with a custom type called ColumnSetting, which is a subset of another type called Column. The original Column type has most properties listed as optional: type ColumnSetting = Pick<Column, 'colId' | 'width' | 'sort ...

Utilizing RavenDB with NodeJS to fetch associated documents and generate a nested outcome within a query

My index is returning data in the following format: Company_All { name : string; id : string; agentDocumentId : string } I am wondering if it's possible to load the related agent document and then construct a nested result using selectFie ...

During rendering, the instance attempts to reference the "handleSelect" property or method which is not defined

I've incorporated the Element-UI NavMenu component into my web application to create a navigation bar using Vue.JS with TypeScript. In order to achieve this, I have created a Vue component within a directory called "navBar," which contains the follow ...

Using Angular, create mat-checkbox components that are dynamically generated and bound using

In my Offer class, I have a property called "units" which is an array of objects. export class Offer { public propertyA: string; public propertyB: string; public units: Unit[]; } export class Unit { public code: string, public name: ...

Matching TypeScript search field names with column names

Seeking ways to create an API that allows admins to search for users in the database using various fields. // Define allowed search fields type SearchFieldType = 'name' | 'memberNo' | 'email' | 'companyName'; const ...

Error encountered with TypeScript compiler when using a React Stateless Function component

I am attempting to create a React Stateless Function component using TypeScript. Take a look at the code snippet below: import * as React from 'react'; import {observer} from 'mobx-react'; export interface LinkProps { view: any; ...

Is there a way to both add a property and extend an interface or type simultaneously, without resorting to using ts-ignore or casting with "as"?

In my quest to enhance an HTMLElement, I am aiming to introduce a new property to it. type HTMLElementWeighted = HTMLElement & {weight : number} function convertElementToWeighted(element : HTMLElement, weight : number) : HTMLElementWeighted { elemen ...

Encountered an error while attempting to compare 'true' within the ngDoCheck() function in Angular2

Getting Started Greetings! I am a novice in the world of Angular2, Typescript, and StackOverflow.com. I am facing an issue that I hope you can assist me with. I have successfully created a collapse animation for a button using ngOnChanges() when the butto ...

Check out the computed typescript types

In my work with TypeScript types, I find myself frequently using Omit, Pick, and similar tools based on other types. While it generally gets the job done, I often struggle with readability when dealing with complex type manipulations. I am interested in f ...

What is the issue when using TypeScript if my class contains private properties while the object I provide contains public properties?

I am currently facing an issue while attempting to create a typescript class with private properties that are initialized in the constructor using an object. Unfortunately, I keep encountering an error message stating: "error TS2345: Argument of type &apos ...

Is it possible to easily organize a TypeScript dictionary in a straightforward manner?

My typescript dictionary is filled with code. var dictionaryOfScores: {[id: string]: number } = {}; Now that it's populated, I want to sort it based on the value (number). Since the dictionary could be quite large, I'm looking for an in-place ...

Combining enum values to create a new data type

Exploring the implementation of type safety in a particular situation. Let’s consider the following: const enum Color { red = 'red', blue = 'blue', } const enum Shape { rectangle = 'rectangle', square = 'square ...

Tips for crafting a test scenario for input alterations within Angular

Hello there, currently I am working on an application using Angular and TypeScript. Here is a snippet of my template code: <input type="text" placeholder="Search Results" (input)="searchInput($event)"> And here is the TypeScript code for the searc ...

The specified property cannot be found within the type 'JSX.IntrinsicElements'. TS2339

Out of the blue, my TypeScript is throwing an error every time I attempt to use header tags in my TSX files. The error message reads: Property 'h1' does not exist on type 'JSX.IntrinsicElements'. TS2339 It seems to accept all other ta ...

Passing a class as a parameter in Typescript functions

When working with Angular 2 testing utilities, I usually follow this process: fixture = TestBed.createComponent(EditableValueComponent); The EditableValueComponent is just a standard component class that I use. I am curious about the inner workings: st ...

You cannot call this expression. The type 'String' does not have any call signatures. Error ts(2349)

Here is the User class I am working with: class User { private _email: string; public get email(): string { return this._email; } public set email(value: string) { this._email = value; } ...

Discover the steps to extend static generic methods in Typescript

My issue lies in compiling Typescript code as the compiler doesn't seem to recognize the inheritance between my classes. Whenever I attempt to compile, an error arises: Property 'create' does not exist on type 'new () => T'. ...

TypeScript has encountered an issue where a specific type A cannot be assigned to another type A, even though

Encountering a Typescript issue where it claims that type A is not compatible with type A, even though they are identical: Check out this playground link for the code snippet in context: declare interface ButtonInteraction { user: any; customId: strin ...

Verify if the specified key is present in the type parameter and if it corresponds to the expected data type in the value parameter

I have a specific goal in mind: export interface GCLPluginConfig { [key: string]: string | number | boolean | Date | string[]; } export interface CorePluginConfig extends GCLPluginConfig { "core.lastUpdateCheck": Date; } export interface An ...