Replace interface with a string

Is it possible to override an interface with a string in TypeScript?

Consider this example:

type RankList = "Manager" | "Staff"

interface EmployeeList {
    id: string,
    name: string,
    department: string,
    rank: "Staff",
    manager: string
}

interface EmployeeList {
    id: string,
    name: string,
    department: string,
    rank: "Manager"
}

In this scenario, if the employee is listed as a "Manager," they do not have a "manager" field. However, if their rank is "Staff," then the field will have a mandatory "manager" field indicating who their manager is.

So far, I have used an optional field like this:

interface EmployeeList {
    id: string,
    name: string,
    department: string,
    rank: RankList,
    manager?: string
}

But I would like to make it more stringent. Is there a way to achieve this?

Answer №1

If you're seeking a solution, consider using a discriminated union type. This involves creating a type or interface that contains common fields such as id, name, and department, along with separate interfaces for both Manager and Staff. By defining an employee type that serves as a union of both staff and manager types:

type PositionList = 'Manager' | 'Staff';

interface EmployeeInfoCommon {
  id: string;
  name: string;
  department: string;
}

interface ManagerInfo extends EmployeeInfoCommon {
  position: 'Manager';
}

interface StaffInfo extends EmployeeInfoCommon {
  position: 'Staff';
  supervisor: string;
}

type EmployeeInfo = StaffInfo | ManagerInfo;

Check out this playground link for more information.

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

Converting a C# Dictionary<string,string> to a TypeScript Map<string,string>

Struggling to find the best approach for handling key:value pairs in TypeScript when receiving a dictionary object from the C# backend. Everything attempted so far has not yielded the expected results. This is the C# code snippet: var displayFields = ...

Lazy loading implemented with BootstrapVue's b-nav component

Having some trouble wrapping my head around the following issue: I've created a Vue.js component with tabs that have routes. I opted for a variation of the b-nav Tabs style (official docs) and it's functioning well in terms of tabs and routing. ...

How can parameters be implemented in Angular similar to NodeJs Express style?

Is there a way to implement a Parameter in Angular routes that resembles the NodeJs style? I have a route like **http://myhost.domain.com/signin**" and I want to pass an id for the signin request. Although I can achieve this using **http://myhost.doma ...

Typescript error in React: The element is implicitly of type any because a string expression cannot be used to index type {}

I'm currently working on grouping an array by 'x' in my React project using TypeScript, and I've encountered the following error message: Element implicitly has an 'any' type because expression of type 'string' can&a ...

The resurgence of React JS in its role as a powerful tool

Although I struggle with React JS, I couldn't find a solution for this particular issue. I'm trying to incorporate this function into my tsx file and display it on the screen within a component. function displayUsers() { const UserListComponent ...

React dynamic table

I've been experimenting with creating a dynamic table in React that allows users to add and delete rows. I need the data entered by the user to be saved, possibly using in-state management so that I can work with it later. Essentially, I'm looki ...

There is an error appearing in my .ts code: [ts] The property 'name' is not found in type 'any[]'

While my coding is working fine and data is showing on the page, there seems to be an error occurring in the VSE editor. It is showing something like this: [ts] Property 'name' does not exist on type 'any[]'. This is a snippet of my ...

Tips for triggering an error using promise.all in the absence of any returned data?

I'm dealing with an issue in my project where I need to handle errors if the API response returns no data. How can I accomplish this using Promise.all? export const fruitsColor = async () : Promise => { const response = await fetch(`....`); if( ...

React Typescript is causing issues with the paths not functioning properly

Looking to simplify my import paths and remove the need for deeply nested paths. Currently working with React and TypeScript, I made adjustments to my tsConfig file like so: { "compilerOptions": { "baseUrl": "src", & ...

"Choose one specific type in Typescript, there are no in-b

Need help returning an object as a fetch response with either the property "data" or "mes": { data: Data } | { mes: ErrMessage } Having trouble with TypeScript complaining about this object, let's call it props: if (prop.mes) return // Property &a ...

Using mergeMap in conjunction with retryWhen allows for the resumption of retries from the exact point of failure, without needing

I have a list of URLs, the number of which is unknown until it stops (depending on some condition). This is how I am currently using them: from(observableUrls) .pipe( mergeMap(url => callHttpService(url) , 4), retryWhen( // Looking f ...

Having trouble importing Sequelize in Angular?

I'm encountering an issue in my app where I am unable to import the sequelize package. The error message reads: chunk {main} main.js, main.js.map (main) 2.02 kB [initial] [rendered] chunk {polyfills} polyfills.js, polyfills.js.map (polyfills) 691 b ...

What is the process of overriding a method from an abstract class that employs generics for typing?

In my quest to develop an abstract class with an abstract static method, I find myself wanting to override this method in a concrete class. The static nature of the method stems from its responsibility to create a 'copy' from a database model and ...

Implementing tailwindcss styles in a typescript interface with reactjs

In my code, I have a file named types.ts that defines an interface called CustomCardProps. I pass this interface to the CustomCard component within the home.tsx file. Additionally, I have a folder named constant with an index.ts file where I store values o ...

Is it possible to enforce strict typing for a property within an object that is declared as type 'any'?

In my code, I am dealing with a parent object of type 'any' that remains constant and cannot be changed. Within this context, I need to define a property for the parent object, but no matter what I try, it always ends up being loosely typed as &a ...

When upgrading from ng15 to ng16, beware of the error message stating that the type '(event: RouterEvent) => void' cannot be assigned to type '(value: Event_2) => void.'

section, I encountered issues with my Angular project after upgrading from ng15 to ng16. Specifically, errors are arising when trying to implement the code snippet below. Can anyone provide insights on what may be causing problems with the event argument ...

Is it possible to retrieve a value obtained through Request.Form?

Within my Frontend, I am passing an Object with a PersonId and a FormData object. const formData = new FormData(); for (let file of files){ formData.append(file.name, file,); } formData.append('currentId',this.UserId.toString()); const upl ...

experiencing an excessive amount of re-renders after transferring data to a distinct component

At the moment, I have implemented this logic to display data based on the results of a graphql query, and it is working well: const contacts = () => { const { loading, error, data } = useUsersQuery({ variables: { where: { id: 1 }, ...

Leveraging cloud functions on Firebase for maximum efficiency

Question: Do you require a backend language when using Firebase Cloud Functions, or can TypeScript alone suffice for coding tasks like creating a matchmaking system? Response: There seems to be some uncertainty on the matter even from ChatGPT himself. Is ...

The selected image should change its border color, while clicking on another image within the same div should deselect the previous image

https://i.sstatic.net/jp2VF.png I could really use some assistance! I've been working on Angular8 and I came across an image that shows how all the div elements are being selected when clicking on an image. Instead of just removing the border effect f ...