Accepting both array and non-array values in the setter function helps to address the issue of accommodating various

In my Angular component, I have an input that typically works with an array of strings:

@Input() names: string[]

<my-comp [names]="['Adam', 'Betty']"></my-comp>

However, I would like to offer an alternative syntax where the user can provide a single value without needing to include brackets:

<my-comp names="Adam"></my-comp>

To achieve this, I aim to handle it in the setter as follows:

private _names: string[];
@Input() set names(value: string[] | string) {
  this._names = Array.isArray(value) ? value : [value];
}
get names(): string[] {
  return this._names;
}

Despite this solution, TSLint brings up error TS2380 which mentions that the accessors should have the same type.

So, my question is: Is there an elegant TypeScript approach to address this scenario?

Answer №1

When it comes to property accessors, TypeScript treats them like actual property and enforces strict rules.

One simple solution is to give the getter/setter different names, for example:

private _names: string[];

@Input() set names(value: string[] | string) {
  this._names = Array.isArray(value) ? value : [value];
}

get namesArray(): string[] {
  return this._names;
}

Alternatively, in Angular, you can map the input name directly like this:

names: string[];

@Input('names') set namesMixed(value: string[] | string) {
  this.names = Array.isArray(value) ? value : [value];
}

This way, you can avoid using a private property altogether.

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

Stop any modifications to the input data

We are currently in the process of building an angular application with Angular 5. Typically, our components have input and output parameters defined as shown below: export class MultipleItemPickerComponent implements OnInit { @Input() itemPickerHeader ...

What sets apart an inlined return type from a return type defined in a separate type definition within a function?

I'm experiencing inconsistent behavior when I specify the return type of a function inline compared to defining it in a separate type definition. For instance: interface Foo { bar: string; } type Fooer = () => Foo; const foo1: Fooer = () =& ...

Converting a dynamic JSON object into a generic type in TypeScript

I need assistance with converting a JSON object into the equivalent generic type in TypeScript. The JSON object I have contains dynamic keys such as applications and permissions. The keys inside applications, like application_management and user_managemen ...

Using TypeScript to utilize an enum that has been declared in a separate file

Imagine I have defined an enum in one file (test1.ts): export enum Colors{ red=1, blue=2, green=3 } Then in another file (test2.ts), I am creating a class with a method. One of the parameters for that method is a Color from the Colors enum: ...

Typescript interface created specifically for React Higher Order Component Props

Consider the React HOC provided below which adds sorting state to a component: import React, {Component, ComponentClass, ComponentType} from 'react' interface WithSortState { sortOrder: string } interface WithSortInjectedProps { sortO ...

Anticipated outcome is the need to provide a value upon completion of arrow function recursion (consistent-return)

If I have a recursive function like the example provided, is it possible to simply return false after the recursive foo call? function foo(fn, redo, interval = 1000) { return new Promise( (resolve, reject) => { fn() .then(resolve) ...

Can you guide me on how to specify the return type in NestJS for the Session User in a request?

async authenticated(@Req() request: Request) { const user = request.user return user } It is important for the 'user' variable to have the correct type globally. While working with express passport, I came across the following: decl ...

Guide to implementing ion-toggle for notifications with Ionic 2 and Angular 2

Currently, I am using a toggle icon to set the notification as active or inactive. The response is obtained from a GET call. In the GET call, the notification value is either 0 or 1, but in my TypeScript file, I am using noteValue as boolean, which means w ...

Unexpected alteration of property value when using methods like Array.from() or insertAdjacentElement

I'm encountering an issue where a property of my class undergoes an unintended transformation. import { Draggable, DragTarget } from '../Models/eventlisteners'; import { HeroValues } from '../Models/responseModels'; import { Uti ...

What is the best way to combine two calls into a single condition check in React using Typescript?

Does anyone have suggestions on how to tackle this issue? I'm encountering difficulty as it is contained within a tag, which means it adheres to specific rules that I am unfamiliar with. The task involves generating a graph, and when the expandGraph v ...

Generating dynamic content

I require assistance with a programming issue. I am working with two separate components: Stage and Executor. Within the Stage component, I am attempting to create new elements based on input parameters, while in the Executor component, I set these paramet ...

Angular2 Error: Issue with the "match" function in JavaScript

Why am I receiving a typeerror that says "cannot read property of 'match' undefined"? var numInput = document.getElementById('input'); // Listen for input event on numInput. numInput.addEventListener('input', function(){ ...

TypeScript failing to recognize dependency for LitElement

Currently, I am encountering an issue with importing two lit elements in my project, namely RootElement and CustomElement. The problem arises when trying to import CustomElement, which unlike RootElement does not show up properly on the UI. My attempt to i ...

Tips for resolving the issue when Chrome is able to load the page but Postman cannot find it

I'm encountering a perplexing situation that is entirely new to me and difficult to comprehend. I find myself unable to decipher what exactly I am witnessing, leading to uncertainty about why it is occurring, not to mention the challenge of determinin ...

How can you dynamically disable a radio option button using Angular rendering without relying on an ID?

Is there a way to disable the male radio button without using an id, and utilizing angular rendering2? It seems like it's not working for me. I need to make this change only in the form.ts file, without altering the HTML code. form.html <label& ...

Generic Typescript abstract method error: "the class specifies the property as an instance member, but the extended class defines it as an instance member function."

Upon exploring the code in this playground link, abstract class Base<F extends () => void> { public abstract __call__: F; } type CallSignature<T> = { (): T; (value: T): void; } class Foo<T> extends Base<CallSignature&l ...

Using TypeScript with Vue allows you to customize the default export of Vue

Currently experimenting with Vue and TypeScript, attempting to compile to AMD in my tsconfig file. The type definition in vue/types/index.d.ts for Vue.js includes: export default Vue; However, this results in TypeScript compiling it like this: import V ...

Provide the remaining arguments in a specific callback function in TypeScript while abiding by strict mode regulations

In my code, I have a function A that accepts another function as an argument. Within function A, I aim to run the given function with one specific parameter and the remaining parameters from the given function. Here's an example: function t(g: number, ...

Angular route fails to load the HTML file

In the process of developing a route within an Angular application, I have successfully implemented 3 routes. However, one particular route is giving me trouble. I have three folders that need to redirect HTML based on the option chosen. In Angular, I cre ...

Using selectors and mappers in Typescript generics

I am looking to create a versatile selector and mapper method. interface State { user: { name: string; age: number; } } const pickName = (state: State) => state.user.name; const selectAge = (state: State) => state.user.age; ...