How can I specify the type of an object in Typescript to mirror a class's properties as a list?

This demonstration is kept simplistic and straightforward, yet the ultimate objective is far more intricate. It is crucial to grasp the method behind achieving this.

Let's assume there exists a class

class Foo {
  bar: string;
  baz: number;
  bob: any; // could be a function

  bad() {
    return true;
  };
}

and also a function

const init = (options: InitOptions, bar?: string, baz?: number, bob?: any) => {
  const foo = new Foo();
  foo.bar = bar ?? options.fallbacks.bar;
  foo.baz = baz ?? options.fallbacks.baz;
  foo.bob = bob ?? options.fallbacks.bob;
}

The question arises - how can one structure the type InitOptions to replicate the following pattern

type InitOptions = {
  fallbacks = {
    bar: string;
    baz: number;
  }
}

while avoiding redundancy? For instance, fallbacks should form an object where each key corresponds to a property within Foo.

Answer №1

Is it really that simple?

class ConfigOptions 
{
  defaults: Bar;
}

Revised for better understanding:

{
  defaults: Choose<Bar, keyof Bar>;
}

Answer №2

Why not consider using the traditional OO inheritance approach?

class Fooable {
  bar: string = '';
  baz: number = 0;
}

class Foo extends Fooable {
  bad() {
    return true;
  }
}

class InitOptions {
  fallbacks: Fooable = { bar: '', baz: 0 };
}

function init(options: InitOptions, bar?: string, baz?: number) {
  const foo = new Foo();

  foo.bar = bar ?? options.fallbacks.bar;
  foo.baz = baz ?? options.fallbacks.baz;

  console.log(`Initialized with bar: ${foo.bar}, baz: ${foo.baz}`);
}

init({ fallbacks: { bar: 'Hello', baz: 123 } });
init({ fallbacks: { bar: 'Hello', baz: 123 } }, 'World', 456);

When executed with ts-node version 10.2.1, the output is as follows:

Initialized with bar: Hello, baz: 123
Initialized with bar: World, baz: 456

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

I am experiencing issues with the Link component in Next.js version 13.4, as it

Whenever I attempt to navigate by clicking on the buttons labeled About, Experience, and others, the page does not redirect me accordingly. Oddly enough, if I manually input the endpoint for that specific page like http://localhost:3000/#about, it function ...

Exploring the Realm of Javacript Template Literal Capabilities

Is it possible to define a variable inside a template literal and then utilize it within the same template? If this isn't feasible, it appears to be a significant feature that is lacking. const sample = tag` some random words, ${let myvar = 55} addit ...

A special function designed to accept and return a specific type as its parameter and return value

I am attempting to develop a function that encapsulates a function with either the type GetStaticProps or GetServerSideProps, and returns a function of the same type wrapping the input function. The goal is for the wrapper to have knowledge of what it is ...

Update the js file by incorporating the import statement

Currently, I am in the process of transitioning to using imports instead of requires for modules. Here is an example of my previous code: const { NETWORK } = require(`${basePath}/constants/network.js`); The content of network.js file is as follows: export ...

Utilizing Angular2 with Webpack in Visual Studio 2015

Is there a way to utilize Visual Studio 2015 alongside Webpack and Angular2? I have successfully created an Angular2 App with VS, but now that I've added Webpack to build my app, I would like to debug all of my code using IIS Express. I want to be abl ...

Automating button clicks after a component has loaded in Angular 2+ can be achieved by implementing a

Currently, I am working on implementing an automatic search function in Angular that triggers after a component loads. Right now, the function is triggered by a button click, but I want to automate this process. <button mat-raised-button class="mat-whi ...

Guide to initializing the state in pinia with Typescript

I am encountering an issue while trying to add typescript to a pinia store. Any suggestions on how to resolve this problem would be appreciated. The project currently utilizes pinia:^2.0.16 and Vue:3.2.37 The error message is as follows: Type '{}&a ...

Due to the feature in VISUAL STUDIO CODE that presents folders and subfolders at the same level

While working on my Angular project, I encountered an issue with creating a subfolder within a folder. Despite trying the same process in Windows Explorer, I faced the same problem of them appearing on the same level. What could be causing this discrepan ...

Understanding DefinitelyTyped: Deciphering the explanation behind 'export = _;'

Having trouble integrating angular-material with an ng-metadata project and encountering some issues. Utilizing DefinitelyTyped for angular material, the initial lines are as follows: declare module 'angular-material' { var _: string; expo ...

Mono repo project utilizing Angular 4+ and Typescript, enhanced with Bootstrap styling

Looking for a project to practice with Angular 4+ using Typescript and a Bootstrap template. Hoping for a setup where I can just run npm install and ng serve to start. Any recommendations for mono repos would be highly valued! ...

Error: Failed to execute close function in inappbrowser for Ionic application

Working on integrating the "in-app-browser" plugin with my Ionic project. Check out the code snippet below: const browser = this.iab.create(mylink, '_blank'); browser.on('loadstop').subscribe( data => { if ...

Angular 14: A collection and schematic must be provided for execution to proceed with the process

I've recently started learning angular. After installing the latest version, I created an app called "test" using the command ng new test. Next, I opened the app in Visual Studio Code and tried to create a new component by entering the command: ng g ...

Tips for displaying an associative object array as td elements within a tbody in Nuxt

I'm having trouble displaying the property of an associative object array in my code. I attempted to utilize a v-for loop and wanted to showcase the property information within the td elements of a tbody. I am aware that v-data-table components have a ...

Tips for properly waiting for an AngularFire2 subscription to complete before executing the subsequent lines of code within Angular2

Having an issue with my Angular2 Type Script code. The goal is to access Questions from a Firebase Database by subscribing to a FirebaseListObserver: this.af.list('/questions').subscribe( val => { this.questions = val console.log(th ...

Encountering a type error with mongoose's pre-save method while using Express with TypeScript

Currently, my tech stack consists of Express.js in TypeScript with Mongoose. Here is the model I am working with: import mongoose, { Schema, Document, Model } from 'mongoose'; import crypto from 'crypto'; import validator from 'val ...

The node version in VS Code is outdated compared to the node version installed on my computer

While working on a TypeScript project, I encountered an issue when running "tsc fileName.ts" which resulted in the error message "Accessors are only available when targeting ECMAScript 5 and higher." To resolve this, I found that using "tsc -t es5 fileName ...

Anyone have any suggestions on how to resolve the issue with vertical tabs in material UI while using react.js?

I'm working on integrating a vertical tab using material UI in react.js, but I'm facing an issue where the tabs are not appearing. Here is the snippet of my code: Javascript: const [value, setValue] = useState(0); const handleChange1 = (event ...

Pass information captured from Mat Dialog up to the main component

Looking for a way to pass true/false boolean data from a dialog box into the parent component without just console logging the result? You want to store it in a variable in the parent component for further use. Any suggestions on how to achieve this? This ...

Encountering a Javascript error while trying to optimize bundling operations

After bundling my JavaScript with the .net setting BundleTable.EnableOptimizations = true;, I've encountered a peculiar issue. Here's the snippet of the generated code causing the error (simplified): var somVar = new b({ searchUrl: "/so ...

The TypeScript class for Date has a property that outputs a string

In my TypeScript code, I have defined a model class as follows: export class Season { ID: number; Start: Date; } Below is an example of how this model class is utilized within a component: export class SeasonsComponent { seasons: Season[]; sele ...