A private class member becomes necessary for stubbing a class

While trying to stub out a class for testing, I encountered errors indicating that private members are missing. This is unexpected as TypeScript should only concern itself with public members accessible from the outside.

The error states: 'Property 'a' is missing in type '{ b: () => number; }' but required in type 'MyClass'.(2741)'

class MyClass {
    private a() {
        return 1
    }

    public b() {
        return 2
    }
}

const test: MyClass = {
    b: () => 2
}

Click here for a Typescript Playground implementation.

I am puzzled by why TypeScript demands private member implementations in this scenario.

What workaround would you suggest for this?

Answer №1

Discover a solution that works for me at: https://github.com/microsoft/TypeScript/issues/18499#issuecomment-429272545

class MyClass {
    private a() {
        return 1
    }

    public b() {
        return 2
    }
}


type Public<T> = { [P in keyof T]: T[P] }

const test: Public<MyClass> = {
    b: () => 2
}

Although it seems unnecessarily complicated, I found a workaround for TypeScript's requirement of implementing private members. These members are inaccessible anyway, so it's puzzling why they need to be included.

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

Dealing with compilation errors in TypeScript

I'm working on a simple TypeScript program that looks like this - const users = [{ name: "Ahmed" }, { name: "Gemma" }, { name: "Jon" }]; // We're trying to find a user named "jon". const jon = users.find(u => u.name === "jon"); However, wh ...

Arranging an array of objects in Angular 7 according to the order of another array of objects

Yes, I know this question has been asked a million times before. However, I haven't found any helpful answers in those previous questions. Here's my dilemma: I have two arrays containing two different objects, each with a unique string property ...

How to Handle ISO 8601 Dates in Angular2 Using DatePipe?

I recently attempted to implement a basic date pipe in my angular2 application: Registered: {{user.registered | date:'shortDate'}} However, I encountered the following error: Invalid argument '2016-03-28T07:25:40.824Z' for pipe &apos ...

Guide to generating external source maps for using the Chrome debugger in Vscode with Typescript and Gulp for web development

Seeking to utilize Gulp for the development of my straightforward Typescript project that runs in the browser. When using gulp-typescript, it seems to insert modules.export into the generated js files, leading me to explore some examples involving browseri ...

Alert displaying NextJS props

I recently began learning Next.js and have encountered an issue while trying to pass props from a parent component to a child component. The error message I'm seeing is: Type '({ name }: { name: any; }) => JSX.Element' is not assignable ...

Error TS6200 and Error TS2403: There is a conflict between the definitions of the following identifiers in this file and another file

Currently working on setting up a TypeScript node project and running into issues with two files: node_modules@types\mongoose\index.d.ts node_modules\mongoose\index.d.ts Encountering conflicts in the following identifiers when trying ...

Guide to transforming JSON data into a different structure

My API is currently providing data in this format: [ { "lattitude": 52.57812538272844, "longitude": -1.7111388218750108, }, { "lattitude": 53.043884, "longitude": -2.923782, } ] I need to transform the data ...

Removing Chosen Row in Angular - A Step-by-Step Guide

My issue involves a <mat-radio-button> list. I am encountering an error where the first radio button stops functioning after toggling between the first and second buttons. Additionally, when I click the delete button, it deletes both the first and se ...

Validate that the input is an array

Looking for a way to determine if a function parameter is an array or not, and then process it accordingly. If the parameter is not an array, convert it into an array before performing the desired function. For example: interface employee { first: st ...

swap out a single amchart for a different one

Here's the current amchart I have: https://i.sstatic.net/J8QLl.png I'm looking to create another amchart with the same data. Essentially, I want to replace the existing graph. You can find the new chart here -> This is my Angular code: pre ...

What does Angular 5 offer in terms of functionality that is equivalent to?

I am working on my AngularJS 1.5 application where I have controllers directly calling service functions. What is the recommended approach to achieve this in Angular? $scope.permissions = ClockingMenuService.permissions; $scope.data = ClockingMenuService ...

Tips for synchronizing the display of a table with the server response in an Angular application

* Project I am currently working on a project that involves retrieving player data from a json server and displaying it in a standard table format with a paginator. * Issue The challenge I'm facing is ensuring that the table data is loaded before th ...

Exploring the Use of Overloads and Callbacks in TypeScript

Currently, I am exploring the implementation of the builder pattern and trying to create functions that support optional parameters as arguments. Here is an example of how I am approaching this: new Service().OnAction(Actions.Add, () => { alert(1); }) ...

How to retrieve the value of a static property within an anonymous class in TypeScript

When a class is defined like the following in a file named MyClass.ts: export default class { static someProperty = 1; someMethod() { var a = ????.someProperty } } How can we access someProperty? The code this.someProperty will not w ...

The default value in an Ionic select dropdown remains hidden until it is clicked for the first time

Having an issue with my ion-select in Ionic version 6. I have successfully pre-selected a value when the page loads, but it doesn't show up in the UI until after clicking the select (as shown in pic 2). I'm loading the data in the ionViewWillEnt ...

Ways to verify whether any of the variables exceed 0

Is there a more concise way in Typescript to check if any of the variables are greater than 0? How can I refactor the code below for elegance and brevity? checkIfNonZero():boolean{ const a=0; const b=1; const c=0; const d=0; // Instead of ma ...

A guide to setting initial values in Angular 2 using TypeScript

My Rank class includes attributes for "loses" and "wins" obtained from a web service. I need to calculate the "points" attribute based on these values. For example: for(int i = 0; i<loses; i++{ points += 1; } for(int i = 0; i<wins; i++{ point ...

Angular Universal application encounters an error: NullInjectorError when trying to access ChildrenOutletContexts in AppServerModule

Embarking on the journey of creating a CRUD app walk through for an Angular Universal with server-side rendering using MongoDB. While I have dabbled in simple single page Angular applications involving forms and validations, this marks my first encounter w ...

Is node.js necessary for running TypeScript?

Node.js is necessary for installing TypeScript. I believe that TypeScript utilizes Node.js to compile .ts files into .js files. My concern is whether the generated .js file needs node.js in order to function properly. From what I've observed, it seem ...

What is the best way to include a string index signature in a preexisting Array?

Currently, I am immersed in styled-system and attempting to define a pattern that is frequently employed within the library. const space: { [key: string]: string } = [ '0.25rem', '0.5rem', '1rem', '2rem', ...