Utilizing arrays to generate dynamic types within a class method

Is there a way to extract values from an array as specific types in TypeScript?

const chars = ['a','b','c'] as const

type TChars = typeof chars[number] // 'a'| 'b' | 'c'

I want to achieve the same behavior for methods and properties within a class, like this:

class Test{
  constructor(public chars:string[]){}

  get(char:string){
    return char
  }
}

new Test(['a','b','c']).get('d') //error only allow a,b or c

This means that the get() method should restrict input to the initial characters passed to the constructor.

I am willing to modify the class signature if necessary.

TS Playground

Answer №1

Essentially the same method, with a slight twist - you must designate the class as generic and then utilize that generic to specify that get will only accept values within the array.

Check out this example on TS Playground!

class Test<T extends readonly string[]> {
  constructor(public chars: T) {}

  get(char: T[number]) {
    return char;
  }
}

//error only allow a,b or c
new Test(["a", "b", "c"] as const).get("d");

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

Issue encountered: Nuxt 3 fails to locate the useRoute import

Recently, I updated to the latest version of Nuxt and encountered an issue with the useRoute method. Even though it works, I keep getting a "Cannot Find name useRoute" error message. Can anyone help me figure out what might be missing? <script lang=&quo ...

The assignment of Type Program[] to a string[] is not valid

I am working with a class that contains information about different programs. My goal is to filter out the active and inactive programs, and then retrieve the names of those programs as an array of strings. Below is the structure of the Program class: ex ...

Navigating through the complexities of managing asynchronous props and state in React-components

I'm really struggling to understand this concept. My current challenge involves passing asynchronously fetched data as props. The issue is that the props themselves are also asynchronous. Below is a simplified version of the component in question: i ...

Guide to creating a universal interface using the generic class concept

I am in the process of developing a new augmented, generic interface that is based on an existing interface. The original interface sets out the properties that the object will possess (root). The enhanced type should also have these properties, but instea ...

Merging declarations fails to function properly following the release of the npm module

The file core.ts contains the definition of a class called AnyId. In another file named time.ts, more methods are added to the AnyId class. This is achieved by extending the type of AnyId using declaration merging: declare module './core' { in ...

Clicking on an element- how can I find the nearest element?

Encountering an issue with my next js app where I am attempting to assign a class to an element upon clicking a button. The problem arises when trying to access the next div using the following code snippet: console.log(e.target.closest('.request_quot ...

Generating React Components Dynamically using TypeScript

Attempting to generate an element in React using Typescript based on the given tagName passed as props, along with additional relative element properties depending on that particular tagName. Take a look at the code snippet below: type ElementProps<Tag ...

The state will reset whenever there is a change in values within an object, but this will only occur if I am

What I'm looking to achieve is this: I need to choose a single card view to edit Once editing is done, I want to save the changes Please refer to the video I've uploaded for clarification and can you please explain why this issue is occurring. ...

The promise chain from the ngbModal.open function is being bypassed

I'm currently working on implementing data editing within a component. My task involves checking if any of the data fields have been altered, and if so, prompting a confirmation pop-up to appear. If the user confirms the change, the data will then be ...

Creating a dynamic columns property for Mat-Grid-List

Is it possible to create a Mat-Grid-List where the number of columns can be dynamically changed based on the width of the container? Here is an example: <mat-grid-list [cols]="getAttachmentColumns()" rowHeight="100px" style="width: 100%;"> <mat ...

Transferring the storage value to an Ionic 2 object

Extracting information from storage in Ionic 2. this.storage.get('name').then((nama) => { this.name = nama }); Now, I am trying to assign the extracted data "this.name" to an object. However, upon running the app, ...

Error in StoryBook addon-docs: "No props discovered for this particular component" when utilizing TypeScript

Encountering an issue with a TypeScript and StoryBook project: The table displaying component properties is not generated nor visible in the StoryBook "Docs" tab on a TypeScript-based project setup. Instead of the expected table, a message saying "No pro ...

Assigning object properties from a request to every item in an observable array of objects using RxJS

Despite my efforts to search various resources like mergeMap and switchMap, I am unable to solve the problem I'm facing as I am still new to RxJs. While I would like to provide more details about my attempts in this post, I fear it may complicate my q ...

Error: Unable to locate the tslint command

After attempting to utilize tslint --fix, I encountered the error message bash: tslint: command not found.... To install tslint, I ran the following command: yarn global add tslint typescript. The operating system on my machine is Centos 7. ...

What is the best way to add an item to an array with distinct properties?

I am currently working on creating an array with different properties for each day of the week. Here is what I have so far: const [fullData, setFullData] = useState([{index:-1,exercise:''}]) My goal is to allow users to choose exercises for a sp ...

What is the method to assert that two arguments are equal within a function?

When working with TypeScript, you can pass a value to a function and have that function assert the value is true for type narrowing. For example: function assertTrue(v: unknown, message: string): asserts v { if (!v) { throw new MySpecialError(message ...

Having trouble using the 'in' operator to search for 'Symbol(StrapiCustomCoreController)' while transitioning Strapi to TypeScript

I'm in the process of converting my strapi project to typescript. I've updated all strapi packages to version 4.15.5 and converted the files to ts extension. However, upon running strapi develop, I encounter the following error: [2024-01-03 10:50 ...

I'm feeling lost when it comes to rendering these components using styled-components in reactjs

Include the BarItem and BarItemSelect components inside the link when the condition is true, both styled with a specific CSS class. Currently, these are two separate components... I'm unsure how to achieve this const S = { BarItem: styled.a` pos ...

What is the method for utilizing an alias at the top within a subquery?

Is it possible to use an alias from the top query in a subquery? I am currently encountering an error with 'artc'. let myQuery = this.articles.createQueryBuilder('artc') .select(['artc.title']) .addSelect(qb => ...

Error message in Angular when promises are not defined

Recently, I started working with promises for the first time. I have a function that returns a promise: public DatesGenerator(futercampaign: ICampaign, searchparam: any, i: number): ng.IPromise<any> { return this.$q((resolve, reject) => { ...