Ways to establish the relationship between two fields within an object

These are the definitions for two basic types:

type AudioData = {
  rate: number;
  codec: string;
  duration: number;
};

type VideoData = {
  width: number;
  height: number;
  codec: string;
  duration: number;
};

Next, I need to create a MediaInfo type:

type MediaInfo = {
  type: 'audio';
  data: AudioData;
} | {
  type: 'video';
  data: VideoData
}

Typically, this approach works for me.

However, in certain scenarios - such as defining a field in a database using typeorm - I cannot utilize the | symbol and instead require a structured definition like this:

type MediaInfo = {
  type: 'audio' | 'video';
  data: AudioData | VideoData;
}

Nonetheless, I understand that this method is somewhat ambiguous.

Therefore, my inquiry involves exploring how to define MediaInfo more precisely without relying on the | symbol technique previously employed.

Answer №1


  interface SoundType = {
    aaa: number;
  };
  interface VisualType = {
    bbbb: string;
  };

  interface TypeDictionary = {
    sound: SoundType;
    visual: VisualType;
  };

  type DefinitionConstraints<T extends object> = {
    [Key in keyof T]: {
      essence: Key;
      specifics: T[Key];
    };
  }[keyof T];

  type MultiMediaFormat = DefinitionConstraints<TypeDictionary>;

  let data: MultiMediaFormat = {
    essence: "sound",
    specifics: {
      aaa: 1
    }
  };

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

Anticipating the completion of post requests

I am currently working on implementing a file upload feature in Angular. I have tackled the issue of file size restrictions by creating an API endpoint that can receive file chunks. Once all the chunks are received, another endpoint needs to be triggered ...

Leveraging IntersectionObserver to identify the video in view on the screen

Our Objective I aim to implement a swipe functionality for videos where the URL changes dynamically based on the ID of the currently displayed video. Challenges Faced Although I managed to achieve this with code, there is an issue where the screen flashe ...

Creating TypeScript versions of `delegate` pattern JavaScript code

Looking for a way to convert the following javascript code into typescript? const handlers = { say (msg) { console.log(msg) }, add (a, b) { return a + b } } function caller (method, ...args) { if (handlers[method]) return handlers[methd ...

What is the best way to execute a function from a parent element within the child element?

Currently, I am working with two components - Navbar (parent) and Setting Menu (Child). const Navbar: React.FC = () => { const classes = useStyles(); const [randomState, setrandomState] = useState(false); const randomStateFunction = () =>{ ...

Show pictures stored in S3

I currently have an Amazon AWS S3 Bucket where I store images. Each object in the bucket has its own link, but when I try to open it in a browser, the image downloads instead of displaying directly on the site. This makes it challenging to view the images ...

Order of execution for Angular 2 components

import { Component, OnInit } from '@angular/core'; import { FormGroup, FormControl, Validators, FormBuilder } from '@angular/forms'; import {Router, ActivatedRoute, Params} from '@angular/router'; import { Country } from &ap ...

What is the purpose of a Typescript function that returns a function with a generic type?

I recently stumbled upon a perplexing piece of TypeScript code that revolves around the function componentControl. Despite my efforts, I find myself struggling to fully comprehend its purpose and functionality. componentControl: const componentControl: &l ...

Here is a way to return a 400 response in `express.js` when the JSON request body is invalid

How can I make my application send a response with status code 400 instead of throwing an error if the request body contains invalid JSON? import express from 'express' app.use(express.urlencoded({ extended: false })) app.use(express.json()) ...

Issues with displaying data in Angular Material table

I am having trouble displaying data in a table. The data shows up when I display it in another element, but not in the table. Here is my code: <mat-accordion *ngIf="posts.length > 0"> <mat-expansion-panel *ngFor="let post of p ...

Having trouble loading extensive amounts of data into a select element within an Angular application

Upon successfully retrieving around 14000 data entries from an HTTP request, I am facing difficulties loading this vast amount of data into my Select Tag. This is causing the entire page to slow down. The structure of the select Tag in question is as follo ...

Angular - optional parameter in route using ngRouter

I have a question regarding using Angular (4) with the @angular/router. I want to be able to include optional parameters in a path style, but am facing some challenges. Currently, my code looks like this: { path: 'cars', component: CarComponent ...

What is the best way to connect a toArray function to an interface property?

Consider the following scenario: interface D { bar: string } interface B { C: Record<string, D> // ... additional properties here } const example: B = { C: { greeting: { bar: "hi" } } // ... additional properties here } Now I would like t ...

What could be the reason behind the material table not populating with data from the source, despite the service returning an array?

Currently, I am utilizing a mean stack in order to craft a bug tracking system. The issue arises when my express.js service returns an array of issues, which I assign to another array that functions as the dataSource for mat-table. However, despite the ar ...

Exploring Angular14: A guide to efficiently looping through the controls of strictly typed FormGroups

Currently, I am working on upgrading my formGroups to be strictly typed in Angular v14. Within my FormGroup, there is a specific block of logic that iterates through all the controls and performs an action (this part is not crucial as I am facing issues be ...

Replace the function if it is specified in the object, otherwise use the default functionality

Having a calendar widget written in TypeScript, I am able to bind a listener to a separate function. However, I desire this separate function to have default functionality until someone overrides it in the config object passed to the constructor. Within th ...

execute the function once the filereader has completed reading the files

submitTCtoDB(updateTagForm:any){ for(let i=0;i<this.selectedFileList.length;i++){ let file=this.selectedFileList[i]; this.readFile(file, function(selectedFileList) { this.submitTC(updateTagForm,selectedFileList); }); } } } ...

Ways to solve VScode gutter indicator glitches after switching text editors?

When my active function is running, I have a specific updateTrigger that ensures certain actions are taken when the activeTextEditor in vscode changes: const updateTrigger = () => { if (vscode.window.activeTextEditor) { updateDecorations(con ...

Using TypeScript to style React components with the latest version of Material UI, version

Styled typography component accepts all the default typography props. When I include <ExtraProps> between styled() and the style, it also allows for extra props. const StyledTypography = styled(Typography)<ExtraProps>({}) My query is: when I r ...

Encountered a type error during project compilation: "Type '(e: ChangeEvent<{ value: string[] | unknown; }>) => void' error occurred."

I recently started working with react and I'm facing an issue with a CustomMultiSelect component in my project. When I try to call events in another component, I encounter the following error during the project build: ERROR: [BUILD] Failed to compile ...

Angular does not completely erase everything

Having some issues with file deletion while working on angular and typescript. My setup involves three interfaces: Project, SubProject, and Position. When a subproject is added to the selected project, it gets included in the subProjectIds list of the Proj ...