The collaboration between an object literal declaration and an object instantiated through a constructor function

If I declare let bar: Bar; and set it to initialFooConfig;, is bar still considered as type Bar and an object, or does it become an object in literal notation?

If the assignment can be done both ways (assuming initialFooConfig is not a constant), what sets apart initialFooConfig from initialBarConfig?

interface IFoo {
    code: number;
    name: string;
}

export const initialFooConfig: IFoo = {
    code: 12,
    name: "bar"
}


class Bar implements IFoo { 
    code: number;
    name: string;

    constructor(code: number, name: string) { 
        this.code = code;
        this.name = name;
    }
}

export const initialBarConfig = new Bar(12,"bar");

Answer №1

When it comes to Typescript, there is no distinction between IFoo and Bar because they are essentially identical.

// These three examples are all the same
// There is absolutely no discernible difference
// (except for the names during hover)
type X = {x: number}
interface Y {x: number}
class Z {x: number = 0}

This means you can assign them in any possible way.

During runtime, their values can be whatever you desire. You could use

let y: X | Y | Z = x{1}; // It's essentially the same type regardless
if (y instanceof Z) {} // If it's `Z{x:1}`
if (Object.getPrototypeOf(y) === Object.prototype) {} // If it's `{x:1}`

To determine if it's an instance of a class object.

If you wish to prevent assigning objects to a class, you can do so by

declare class IPrivate {
  #private;
}
const Private = Object as any as typeof IPrivate;

type X = {x: number}
interface Y {x: number}
class Z extends Private {x: number = 0}

let x: X = {x: 0}
let z: Z = {x: 1}
//  ~ Property '#private' is missing in type 'X' but required in type 'Z'.(2741)

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

React - Component not updating after Axios call in separate file

Recently I decided to delve into React while working on some R&D projects. One of my goals was to build an application from scratch as a way to learn and practice with the framework. As I started working on my project, I encountered a rather perplexin ...

How to associate an object with a component in Angular2/TypeScript using HTTP

I am currently working on displaying a list of item names retrieved from a REST API. By utilizing the map function on the response observable and subscribing to it, I was able to obtain the parsed items object. Now, my challenge is how to bind this object ...

Understanding Angular's Scoping Challenges

I have a function that retrieves an array and assigns it to this.usStates. main(){ this.addressService.getState().subscribe( (data:any)=>{ this.usStates = data; if(this.usStates.length===0) { this.notificationServic ...

The type of the element is implicitly set to 'any' because the expression 'keyof IMyObj' cannot be used to index the type

Trying to avoid specifying types in TypeScript and setting a value by accessing its key is causing a TypeScript error. Despite looking at multiple StackOverflow posts, I couldn't find a solution. I encountered a similar issue with my code and tried r ...

The command "ng test" threw an error due to an unexpected token 'const' being encountered

Any assistance with this matter would be greatly appreciated. I am in the process of constructing an Angular 5 project using angular/cli. The majority of the project has been built without any issues regarding the build or serve commands. However, when a ...

Preserving ES6 syntax while transpiling using Typescript

I have a question regarding keeping ES6 syntax when transpiling to JavaScript. For example, if I write the following code: class Person { public name: string; constructor(name: string) { this.name = name; } } let person = new Person('John D ...

Attempting to retrieve a URL using Angular/Typescript is generating an Unknown Error instead of the expected successful response

I'm trying to make a simple HTTP function call through TypeScript (Angular) to an API hosted as a function in Azure. When I call the URL through Postman or directly in the browser, everything works perfectly. However, when I try to call the URL usin ...

The term "containerName" in SymbolInformation is utilized to represent the hierarchy of

In my quest to make the code outline feature work for a custom language, I have made progress in generating symbols and displaying functions in the outline view. However, my next challenge is to display variables under the respective function in the outlin ...

Is there a way to combine multiple array objects by comparing just one distinct element?

Is there a way to combine these two arrays into one? array1 = [ { image: 'image1', title: 'title1' }, { image: 'image2', title: 'title2' }, { image: 'image3', title: 'title3' }, ]; array2 = ...

Error: Failed to load chunk 552 due to chunk loading issue

Currently in the process of migrating Angular 12 to version 13. The migration itself was successful, however, upon running the project in the browser post a successful build, the application fails to display. On checking the console, I encountered the foll ...

Unit test: Using subjects instead of observables to mock a service and test the change of values over time results in TypeScript throwing error TS2339

I have a unique scenario where I have implemented a service that accesses ngrx selectors and a component that utilizes this service by injecting it and adjusting properties based on the values retrieved. For unit testing purposes, I am creating mock versi ...

Positioning customized data on the doughnut chart within chart.js

Is there a way to customize the position of the data displayed in a doughnut chart? Currently, the default setting is that the first item in the data array is placed at 0 degrees. However, I need to place it at a custom position because I am working on a ...

Utilizing Angular signals to facilitate data sharing among child components

I have a main component X with two sub-components Y and Z. I am experimenting with signals in Angular 17. My query is how can I pass the value of a signal from sub-component Y to sub-component Z? I have attempted the following approach which works initial ...

How should one begin a new NativeScript-Vue project while implementing Typescript support in the most effective manner?

Is it possible to incorporate Typescript into Vue instance methods? I found guidance on the blog page of nativescript-vue.org. Whenever I initiate a new nativescript-vue project using vue init nativescript-vue/vue-cli-template <project-name>, some w ...

Discovering subtype relationships in JSON with TypeScript

Consider the scenario where there are parent and child typescript objects: class Parent { private parentField: string; } class Child extends Parent { private childField: string; } Suppose you receive a list of JSON objects for both types via a R ...

Having trouble locating the type definition file for '@types' while working with Ionic 4 and Angular 7

Recently, I made the transition in my ionic 4 project to utilize angular 7. While everything seems to be functioning correctly in debug mode, I encountered an issue when attempting to compile for production using the command 'ionic cordova build andro ...

What is the best way to assign a value to an option element for ordering purposes?

My select element is being populated with fruits from a database, using the following code: <select name="fruitsOption" id="fruitsOptionId" ngModel #fruitRef="ngModel"> <option *ngFor="let fruit of fruits">{{fruit}}</option> </selec ...

Angular - Error: Object returned from response does not match the expected type of 'request?: HttpRequest<any>'

While working on implementing an AuthGuard in Angular, I encountered the following Error: Type 'typeof AuthServiceService' is not assignable to type '(request?: HttpRequest) => string | Promise'. Type 'typeof AuthServiceServic ...

Unexpected TypeError when using Response.send()

Here is a snippet of my simple express code: const api = Router() api.post('/some-point', async (req, res, next) => { const someStuffToSend = await Promise.resolve("hello"); res.json({ someStuffToSend }); }) In my development environmen ...

Using Angular 8, remember to not only create a model but also to properly set it

hello Here is a sample of the model I am working with: export interface SiteSetting { postSetting: PostSetting; } export interface PostSetting { showDataRecordAfterSomeDay: number; } I am trying to populate this model in a component and set it ...