Improving type checking by extracting constant string values from a union type

I am exploring different types of employees:

interface Employee {
    employeeType: string
}

interface Manager extends Employee   { employeeType: 'MANAGER'   // .. etc }

interface Developer extends Employee { employeeType: 'DEVELOPER' // .. etc }

type Staff = Developer | Manager

In order to create a new type that contains all possible string literals for Staff > employeeType, allowing for dynamic updates when new employee types are added:

Here is an example of how it could be manually defined and used:

type EmployeeType = 'DEVELOPER' | 'MANAGER'

The goal is to have the EmployeeType automatically update when a new type of Employee interface is added to the Staff union, like this:

...
interface Designer extends Employee { employeeType: 'DESIGNER' // ..etc }

type Staff = Developer | Manager | Designer

// ... now EmployeeType contains 'DEVELOPER' | 'MANAGER' | 'DESIGNER'

This approach allows for strong type checking in scenarios such as:

function createEmployee(employeeType: EmployeeType, attributes: ...) {
   // ...
}

Instead of using employeeType: string which lacks type safety.

Is there a way to achieve this in TypeScript? Check out this Typescript Playground :)


A related question (using Enums):

Answer №1

To easily access the employeeType property, simply use the employeeType in the Staff object:

type EmployeeType = Staff["employeeType"] // "DEVELOPER" | "MANAGER" | "DESIGNER"

createEmployee('MANAGER') // This will work
createEmployee('SALES')   // This will result in an error

View Sample

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

CDK Error: Unable to locate MethodResponse in AWS API Gateway configuration

I'm facing an issue in vscode while trying to access the MethodResponse interface from apigateway. Unfortunately, I'm getting an error message: The type 'typeof import(".../node_modules/aws-cdk-lib/aws-apigateway/index")' d ...

"Transforming a Java byte array into a ReactJS video: Step-by-step guide

I am getting a file from a Java API server and need to convert it into a video using React JS. The Java API server converts the video file into a byte array using Files.readAllBytes(file) and I need to use this video file byte array to create a video fil ...

Incorporating properties of the parent class through Mixin techniques

I'm encountering an issue while trying to access a property from an inherited class within a mixin class BaseItem{ public id:string; constructor(id:string) { this.id =id; } } abstract class ConfigMixin<K extends BaseItem& ...

Managing Keyboard Input in React using TypeScript

Hey there! I'm currently working on a method that should automatically insert a specific string into a textbox when a particular key is pressed. The key in question is a non-printable character that may not be visible in most font styles, but can sti ...

Different tsconfigs assigned to various directories

In my project, I am using Next.js with TypeScript and Cypress for E2E tests. The challenge I am facing is configuring tsc to handle multiple configs for different folders. The tsconfig.json file in the project root for Next.js looks like this: { "c ...

Is the parent component not triggering the function properly?

Hey there, I'm working with the code snippet below in this component: <app-steps #appSteps [menuSteps]="steps" [currentComponent]="outlet?.component" (currentStepChange)="currentStep = $event"> <div appStep ...

Organize information by time intervals using JavaScript

I am currently facing an issue where I need to dynamically sort data from the server based on different fields. While sorting is working flawlessly for all fields, I am encountering a problem with the time slot field. The challenge lies in sorting the data ...

Function in Typescript that can return multiple data types

I recently started learning about TypeScript and its concepts. During my practice sessions, I encountered a problem that left me puzzled. There is a function named `functionA` which returns an object based on the response received from an API. type Combina ...

Troubleshooting Angular: Unidentified property 'clear' error in testing

I've implemented a component as shown below: <select #tabSelect (change)="tabLoad($event.target.value)" class="mr-2"> <option value="tab1">First tab</option> <op ...

"React's FC generic is one of its most versatile features

I'm currently working on a component that can render either a router Link or a Button based on the provided props. Here is the code snippet I have: import React from 'react'; import Button from '@material-ui/core/Button'; import { ...

The or operator in Typescript does not function properly when used as a generic argument

My current configuration is as follows: const foo = async <T>(a): Promise<T> => { return await a // call server here } type A = { bar: 'bar' } | { baz: 'baz' } foo<A>({ bar: 'bar' }) .then(response =& ...

Error: The variable "prisma" is not defined in this context - Next.js version 14

While working with Prisma and next.js 14, I encountered an issue with the Stripe payment API. The error message ReferenceError: prisma is not defined popped up. How can I resolve this? import { NextApiRequest, NextApiResponse } from "next" import ...

Step-by-step guide on importing CSS into TypeScript

I have a global CSS file where I've defined all the colors. I attempted to import that value into TypeScript but it didn't work. This is my latest attempt: get sideWindowStyle(): any { switch (this.windowStyle) { case 'classicStyl ...

Angular: issue with form validation - password matching is not functioning as expected

I have successfully implemented the registration form with basic validations The code I used can be found in: registration.html <form #registrationForm="ngForm" (ngSubmit)="onFormSubmit()"> ... <div class="form- ...

Inspect the TypeScript typings within Svelte documents directly from the terminal

When I run tsc --noemit, it successfully checks for type errors in the codebase. However, I have encountered an issue where it does not seem to check .svelte files. Is there a way to enable this functionality? I can see the type errors in .svelte files wh ...

The ng-change event fails to trigger when the date change event is activated

Hey there, I'm new to working with AngularJS. I have a scenario where I want a method to be triggered when I change the date, opening a modal. However, when I use the ng-change event, the method is not called upon date change. If I switch to using ng- ...

Transferring client-side data through server functions in Next.js version 14

I am working on a sample Next.js application that includes a form for submitting usernames to the server using server actions. In addition to the username, I also need to send the timestamp of the form submission. To achieve this, I set up a hidden input f ...

Unable to fulfill the return type requirement in a typed TypeScript function

In this scenario, let's consider the following type: export type Transformer = <T extends any[], U>( data: T, ) => U; Now, let's examine a function that needs to adhere to this type: export const transform: Transformer = ( d ...

Combining and linking 3 RxJS Observables in TypeScript and Angular 4 without nesting to achieve dependencies in the result

I have 3 observables that need to be chained together, with the result from the first one used in the other 2. They must run sequentially and each one should wait for the previous one to complete before starting. Is there a way to chain them without nestin ...

Encountering an issue with TypeScript after applying a wrapper to a Material-UI button - specifically, the error message states that the type '{ children: string; color: "light-green"; }' is lacking certain properties

I'm currently working on creating wrapped components using MUI (@material-tailwind/react) within the environment of Next.js 14. However, I've run into a typescript error specifically in the MaterialButton component. Type '{ children: string; ...