Need for utilizing a decorator when implementing an interface

I am interested in implementing a rule that mandates certain members of a typescript interface to have decorators in their implementation.

Below is an example of the interface I have:

export interface InjectComponentDef<TComponent> {
  // TODO: How can I restrict this to only allow properties decorated with @Input()
  inputs: Partial<TComponent>, // & { @Input() [key: string]: any } my attempt to enforce decorator, invalid syntax 
  //... 
};

In the following class example, I aim to prevent the inclusion of the notAnInput property in an InjectComponentDef.inputs implementation:

export class MyComponent {
   public @Input() isAnInput: string;
   public notAnInput: string;
}
...
let x: InputComponentDef<MyComponent> =
{
    inputs: {
        isAnInput:'all good',
        notAnInput:'no good', // I want this to throw a compile time error because it is not decorated with @Input
    }
}

Is there a way to achieve this in typescript at compile time?

Answer №1

According to information sourced from the TypeScript documentation:

During runtime, the class decorator expression is executed as a function, receiving the constructor of the adorned class as its sole argument.

Furthermore:

The decorators ultimately translate into a function that will be invoked at runtime with details regarding the decorated declaration.

From this description, it seems that decorators are not intended for usage during compilation. Even though there may be workarounds to make them function in that context, such an approach could be deemed incorrect from a design standpoint.

To sum up, your scenario seems to involve a situation that cannot be effectively validated during compile time.

Consider why enforcing @Input() is necessary. Perhaps allowing a child object to independently set data for notAnInput might be entirely valid based on your specific requirements.

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

Utilizing ConcatMap in conjunction with an internal loop

I am having a coding issue where I need certain requests to run sequentially, but some of the responses are observables. The data is mainly retrieved except for two requests that need to be executed in a loop for each account. I am using concatMap and fork ...

Using Typescript for testing React components: successfully passing an array of objects as props

My current approach involves passing an array of objects to mock component data for testing: const mockPackage = { id: '1232-1234-12321-12321', name: 'Mock Package', price: 8.32, description: 'Mock description', glo ...

When utilizing an object as state in React, the `setState` function will only set

Currently, I am working on developing a React form that utilizes a custom Input component which I have created multiple times. The objective is to gather all the names and values from the form in the parent component: {inputName: value, inputName2: valu ...

When making a variable call outside of a subscriber function, the returned value is 'undefined'

I find myself in a situation where I have to assign a value to a variable inside a subscriber function in Angular. The issue is that the variable returns 'undefined' when called outside of the Subscribe function. Here's what I'm encount ...

React Quill editor fails to render properly in React project

In the process of developing an application in Ionic React, I am in need of a rich text editor that can save data on Firestore. Despite initializing the editor as shown below and adding it to the homepage component, it is not rendering correctly although i ...

The OnPrepareResponse method in StaticFileOptions does not trigger when serving the index.html file

Currently, I am attempting to disable caching for index.html in my Angular SPA that is connected to a .NET Core 2.2 backend. I am following the instructions provided in this particular answer by implementing an OnPrepareResponse action for my StaticFileOp ...

Tips on incorporating jstree into an Angular 2 application with TypeScript and @types/jstree

Hello, I am new to ng2 and have a question that may seem obvious to some. I recently installed the jstree library using npm in my angular-cli application by running the command npm i jstree --save. Following this, I also installed the types for jstree wi ...

Javascript/Typescript Performance Evaluation

I am looking to create a visual report in the form of a table that displays the count of each rating based on the date. The ratings are based on a scale of 1 to 5. Below is the object containing the data: [ { "Date": "01/11/2022", ...

What is the process for transforming binary code into a downloadable file format?

Upon receiving a binary response from the backend containing the filename and its corresponding download type, the following code snippet illustrates the data: 01 00 00 00 78 02 00 00 6c 02 00 00 91 16 a2 3d ....x...l....... 9d e3 a6 4d 8a 4b b4 38 77 bc b ...

Is it necessary to 'type assert' the retrieved data in Axios if I have already specified the return type in the function declaration?

Consider the code snippet below: import axios from 'axios' async function fetchAPI<T>(path: string, data: any): Promise<T> { return (await axios.get(path, data)).data as T } async function getSomething(): Promise<SomeType> { ...

Tips for adjusting the width of columns automatically in exceljs

One of my challenges is to automatically adjust column width using exceljs. I want the Excel sheet to be dynamic, saving only the columns specified by the user in the request. Here is the code snippet that accomplishes this: workSheet.getRow(1).values = dt ...

Is there a way to position the label to the left side of the gauge?

Is there a way to position the zero number outside the gauge? I'm having trouble figuring out how to do it because the x & y options won't work since the plotLine's position keeps changing. The zero needs to move along with the plotLine and ...

Retrieve the formcontrolname property of a FormGroup within a FormArray

I am currently facing an issue with my code. In my FormGroup, I have a FormArray containing 3 FormControls. My goal is to iterate through the FormArray and display the values of each control in a form. However, I am unsure about what to use for the formCon ...

developing TypeScript classes in individual files and integrating them into Angular 2 components

We are currently putting together a new App using Angular2 and typescript. Is there a more organized method for defining all the classes and interfaces in separate files and then referencing them within angular2 components? import {Component, OnInit, Pi ...

Tips for sorting/merging/consolidating data in Angular

Take a look at this code snippet: rowData = [ [ '2019-12-10 08:00:00', '2019-12-10 08:00:00', '2019-12-10 08:00:00', '2019-12-10 08:00:00', '2019-12-10 08:00:00', '2018-12-10 08:00:00' ...

The function webpack.validateSchema does not exist

Out of the blue, Webpack has thrown this error: Error: webpack.validateSchema is not defined Everything was running smoothly on Friday, but today it's not working. No new changes have been made to the master branch since Friday. Tried pruning NPM ...

Tips for handling user click events in Angular 2?

In Angular2, I am facing an issue with two components. When a user clicks a button in component1, a method is triggered that stores data in the shared service to a variable. However, component2's ngOnInit() method initializes this variable to undefine ...

Angular makes it easy to extract multiple parameters from a URL

In the process of developing a basic Angular application using TypeScript, I have encountered an issue. Within my project, there is a URL structure like this: www.example.com/api/1/countries/Italy/ My goal is to extract the values 1 and Italy from this U ...

"Using RxJS to create an observable that filters and splits a string using

I need to break down a string using commas as separators into an observable for an autocomplete feature. The string looks something like this: nom_commune = Ambarès,ambares,Ambares,ambarès My goal is to extract the first value from the string: Ambarès ...

Typescript offers a feature where we can return the proper type from a generic function that is constrained by a lookup type,

Imagine we have the following function implementation: type Action = 'GREET' |'ASK' function getUnion<T extends Action>(action: T) { switch (action) { case 'GREET': return {hello: &a ...