A method in TypeScript for defining a type as a combination of interfaces within a union, specified as [one of union of interfaces] & {//attributes}

// Here's a way to define types in TypeScript:

interface SudoA {
    foo: string;
}

interface SudoB {
    bar: string;
}

type Sudo = SudoA | SudoB;

type SuperSudo = Sudo & {
    super: boolean;
}

const baz: SuperSudo = {

} 
// TypeScript (3.1.6) requires both `bar` and `foo` properties to be defined in the object

My expectation is to make the super attribute required while allowing other attributes from the Sudo type to be optional. Is this a valid expectation? If not, how can this be achieved?

Edit
I corrected the type of baz, my mistake :/.
I want SuperSudo to only require the super attribute while making other attributes optional.

One approach is to create a new type like

type SuperSudo<T> = T & {}
but this results in using SuperSudo<T> which I find too verbose.

Edit2
Title has been updated

Answer №1

Have you thought about implementing a type discriminator?

If you don't have one, specifying either foo, bar, or both foo and bar will always fulfill the union type.

Implementing one could look like this:

interface SudoA {
  _type: "a";
  foo: string;
}

interface SudoB {
  _type: "b";
  bar: string;
}

type Sudo = SudoA | SudoB;

type SuperSudo = Sudo & {
  super: boolean;
}

const baz1_valid: SuperSudo = {
  _type: "a",
  super: true,
  foo: "bar",
}

const baz2_valid: SuperSudo = {
  _type: "b",
  super: true,
  bar: "foo",
}

The field name doesn't have to be _type; it just needs to be the same field name with different type values on each variant.

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

Filtering React component names and their corresponding values

I am looking to apply filters to React components based on their name and values. Below is the array that needs to be filtered: let filteredArray: any[] = [] const filteredItems: any[] = eventList.filter( (event) => event.printEvent.labels = ...

Creating a dynamic canvas with a three-dimensional model using three.js: A step-by-step guide

I'm currently developing a website where I have integrated a canvas element to display a 3D object (specifically, a cube) using three.js. The canvas is housed within a div, following the guidelines found in various documentation. The issue arises wh ...

How to prevent panning on mobile devices in Three.js using Javscript?

Currently working on my 3D project using three.js and everything is running smoothly on my laptop. I'm utilizing OrbitControls for camera movement, but I have disabled right-click panning to only allow camera rotation. However, when testing on a mobil ...

Is there a way for me to activate onMouseEnter on elements that are positioned behind other elements

I'm attempting to activate the mouseEnter event when the mouse is over multiple elements simultaneously. The goal is for both mouseEnter events to be triggered when the mouse reaches the center, and ideally for both elements to change to a yellow col ...

Is there a method to pre-load a CSS background image so that it can still be displayed even without an internet connection?

Situation: Imagine having a web app that shows an error message when trying to perform an action but fails due to a connectivity problem. The error dialogue has a CSS class with a background image that can't load because of the connection issue, res ...

unable to retrieve the value from the scope

I'm trying to implement the following code in HTML: <div ng-if="item.shareText"> <textarea></textarea> <div> <select ng-model="shareOptions"> <option value="PUBLIC" selected>public</option> ...

What is the purpose of using double quotes within single quotes in JavaScript?

Could someone clarify the reason behind needing to nest double quotes inside single quotes in my Webpack configuration shown below? What is preventing using just double quotes? module.exports = merge(prodEnv, { NODE_ENV: '"development"', API ...

Using Elasticsearch's bulk feature to set unique identifiers(_id) for documents

Whenever I attempt to insert documents into elasticsearch with a set _id, I encounter the following error: The field [_id] is considered a metadata field and cannot be included within a document. It should be utilized in the index API request parameters in ...

Instructions for removing and recreating an input field along with its parent elements when the value of a Select tag is changed

I currently have a table with four fields, as illustrated below: Semester | Exam Status | GPA | Fee Status My query is regarding the behavior when changing the value in Exam_Status: I noticed that the Select tag-> does not clear automatically. Specifi ...

Creating interactive forms - Incorporating dynamic checkbox options within the expansion panel element

Recently, I developed a basic movie list app with a checkbox list for genre filtering. Initially, I managed to achieve the desired functionality without using reactive forms. However, I am now exploring implementing the same functionality using reactive ...

Enhance your React Native experience with IntelliSense recommending react-native/types over react-native

I am trying to bring in <View from react-native, but instead, I am getting react-native/types https://i.sstatic.net/FeRKT.png How can I resolve this issue? This is a new project starting from scratch and I followed the documentation by adding TypeScri ...

I am facing an issue where my video file is not being recognized by Next.js when using TypeScript

In my project using next.js, typescript, and tailwindcss, I encountered an issue while creating the Masthead for my website. I wanted to set a video as the background, but for some reason, the video was not being recognized. I tried moving it to differen ...

Using React to implement MUI autocomplete feature alongside a MUI form

Recently, I have been utilizing a MUI form structured in the following manner: <Box component="form" onSubmit={event => { return handleSubmit(event); }} noValidate sx={{mt: 1}}> <TextField margin="normal" ...

Unexpected patterns observed when utilizing parent/child routing files

I am working with a Node/Express backend that is implemented using TypeScript. Whenever I make changes to a file and save it, if I test the root route in Postman localhost:8000/, I receive the expected response. However, when I test localhost:8000/user af ...

Executing a Function within UseEffect

I need help calling the function onSaveInputValue within the useEffect to make sure that the value is passed to the childInputValue hook whenever the page loads. const onSaveInputValue = (value) => { setChildInputValue(value); consol ...

Rendering DataTable content seamlessly from a different webpage using JavaScript without sacrificing control

Is it possible to dynamically call HTML content from Page2.html into Page1.html by utilizing DataTables (https://datatables.net/)? Page1.html <!DOCTYPE html> <html> <head> <title></title> <meta http-equiv="Content-Type" c ...

Is it feasible to save BoxGeometries or MeshLambertMaterial in an array using Three.js?

var taCubeGeometryArray = new Array(); var taCubeMaterialArray = new Array(); taCubeGeometryArray.push(new THREE.BoxGeometry( .5, .5, .5)); taCubeMaterialArray.push(new THREE.MeshLambertMaterial({map: THREE.ImageUtils.loadTexture( "image.png" )})); Could ...

Trouble with Google Interactive Charts failing to load after UpdatePanel refresh

Desperately seeking assistance! I have spent countless hours researching this issue but have hit a dead end. My dilemma involves using the Google Interactive Charts API within an UpdatePanel to dynamically update data based on dropdown selection changes. H ...

Container for Magazines using HTML and CSS

Looking to develop a digital magazine application with smooth swipe transitions and fade in effects when swiping left and right. I attempted using jQuery.mobile, but struggled with adapting the background image height. My goal is to create a universal web ...

Senecajs responded with a result that was neither an object nor an array, displaying a Promise

Seeking guidance on incorporating promises into my Seneca modules. Firstly, there is the server.js file that exposes a route: var express = require('express'); var app = express(); var Promise = require('bluebird'); var seneca = requ ...