A specialized subtype in Typescript that restricts input to specific string values

I need to figure out the best approach for implementing TypeScript types that only allow specific string values such as:

export type Plan = {
  client_uuid: string;
  name: string;
  kind: string;
};

I want to create a subtype of Plan called Financial, which should only accept the strings "protection" or "insurance", and another subtype called Mortgage that accepts only "mortgage".

Is the following code the only way to achieve this?

export type Plan = {
  client_uuid: string;
  name: string;
};

export type Financial extends Plan {
  kind: "protection" | "insurance"
}

export type MortgagePlan extends Plan {
  kind: "mortgage"
}

It seems like this may not be the most ideal way to create subtypes since it involves re-declaring the kind property each time. Is there a way to specify that a Financial Plan is simply a type of Plan with a restricted kind field?

What other options are available in this situation?

Answer №1

When it comes to extending types, keep in mind that this can only be done with interfaces. To ensure that all fields from the Plan are included, you can utilize an intersection:

export type Plan = {
  client_id: string;
  title: string;
};

export type InsurancePolicy = Plan & {
  type: 'protection' | 'insurance';
};

export type MortgageInsurance = Plan & {
  type: 'mortgage';
};

Answer №2


declare type Policy<T extends boolean> = {
  user_id: string;
  title: string;
  type: T  extends true ?  "protection" | "insurance" : "mortgage"
};


// Policy<true> is Financial
// Policy<false> is MortgagePolicy

multi-category growth strategy:

interface CategoryMap {
  Financial:  "protection" | "insurance"
  MortgagePolicy: "mortgage"
}


declare type Policy<T extends keyof CategoryMap> = {
  user_id: string;
  title: string;
  type: CategoryMap[T]
};

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

Broadening Cypress.config by incorporating custom attributes using Typescript

I'm attempting to customize my Cypress configuration by including a new property using the following method: Cypress.Commands.overwrite('getUser', (originalFn: any) => { const overwriteOptions = { accountPath: `accounts/${opti ...

Prohibit the Use of Indexable Types in TypeScript

I have been trying to locate a tslint rule in the tslint.yml file that can identify and flag any usage of Indexable Types (such as { [key: string] : string }) in favor of TypeScript Records (e.g. Record<string, string>). However, I haven't had a ...

Tips for passing either two parameters or none into a function in TypeScript?

My goal was to enhance a function that simply returns a status. It originally only accepted a logger and a message as parameters for logging purposes. export function status(logger: Logger, reason: string) { logger.info(reason); return { result: &a ...

Manipulating data with Angular 2 services: accessing and updating values

This code snippet is all about managing an array in Angular. The Injectable decorator is used to define a service called Svc with methods for setting and getting column definitions. import { Injectable } from '@angular/core'; @Injectable() ...

Creating Object of Objects in TypeScript: A Comprehensive Guide

Assuming I have a structure similar to this: interface Student { firstName: string; lastName: string; year: number; id: number; } If I intend to handle an array of these structures, I can simply specify the type as Student[]. Instead of utilizin ...

Concealing a column within an Angular Material table

I'm currently faced with a challenge involving an Angular Material table containing numerous columns. My goal is to selectively hide certain columns based on specific CSS media queries. This is the code snippet I have experimented with so far: HTML: ...

Angular Owl Carousel doesn't slide horizontally, it slides vertically

Within my Angular project, I incorporated an Owl Carousel into the home-component.html file. Here is a snippet of the code: <section> <div class="container"> <h1 class="products-title">New Arrivals</h1> ...

What is the process of implementing a particular FormControl from a FormArray in my HTML file?

My FormArray initialization code is as follows: this.contents.forEach(content=> { this.formArray.push( new FormControl(content.text, Validators.required)); }); Now, I am trying to associate a specific FormControl with my textarea by using i ...

The display of the selected input is not appearing when the map function is utilized

I am attempting to use Material UI Select, but it is not functioning as expected. When I use the map function, the default value is not displayed as I would like it to be. However, it does work properly when using the traditional method. *** The Method th ...

Encountering errors in Visual Studio when trying to work with node_modules directories that have a tsconfig

In my current project, there is a tsconfig.json file located in the root directory. Strangely, Visual Studio keeps throwing errors related to other instances of tsconfig.json found in different packages, as shown below: https://i.sstatic.net/T7Co2.png Ev ...

`Is there a way to maintain my AWS Amplify login credentials while executing Cypress tests?`

At the moment, I am using a beforeEach() function to log Cypress in before each test. However, this setup is causing some delays. Is there a way for me to keep the user logged in between tests? My main objective is to navigate through all the pages as the ...

What is the best way to implement this object builder in TypeScript strict mode without adding unnecessary weight to it?

After coming across a builder pattern online that I really liked, I found that it doesn't work in strict mode due to receiving the same error for the first 3 properties: (property) PizzaBuilder.numberOfSlices: number Property 'numberOfSlices&apo ...

What is the step-by-step process for generating a tsconfig.json file within an Angular 2

Recently, I completed setting up an Angular2 project with the help of npm. I followed the instructions from this resource: Angular2 Tutorial After successfully generating the package.json file using the npm init command, I realized that there was no speci ...

Does the value of an Angular reactive form control only reflect what the user inputs?

I am working with a reactive form where I need to extract values and assign them to a variable defined in an interface. The form is populated using the Google Places API, which disables user interaction with all controls except for the initial address inpu ...

Converting object's date property to a new Date() in TypeScript

I am working with a CurrentWeather Model retrieved from localStorage and parsed into an object. export interface CurrentWeather { LocalObservationDateTime: Date; Latitude: string; Longitude: string; LocationKey: string; LocalizedName: s ...

Can you explain the distinctions between QueryBuilder, find, and findOne in TypeORM?

In my typeorm query, I initially used the query builder like this: getManager().CreateQueryBuilder(class_name_from_entity_file, 'xyz').select('column_name').where('active_status=1').execute() While this method gave me the des ...

What is the reason for the failure of the "keyof" method on this specific generic type within a Proxy object created by a class constructor?

I'm encountering difficulties when utilizing a generic type in combination with keyof inside a Proxy(): The following example code is not functioning and indicates a lack of assignable types: interface SomeDataStructure { name?: string; } class ...

The HttpPut request code format is malfunctioning, although it is effective for another request

I'm struggling with a HTTPPUT request that just won't get called. Strangely enough, I have a similar put request that works perfectly fine for another tab even though both pages are practically identical. I've exhausted all options and can&a ...

Guide on converting general objects into a TypeScript class

Having recently started working with Typescript, I have a JSON object that needs to be mapped to a generic interface. However, my initial attempt at creating the interface seems to be incorrect. I need assistance in constructing a generic interface or cl ...

What is the correct way to define a function signature that accepts parameters with union types?

One challenge I am facing is creating an API that requires a function with a parameter that can be either type A or B. To address this issue, I have been utilizing interfaces for typing these parameters. However, the problem arises as these types do not sh ...