Typescript: Declaring object properties with interfaces

Looking for a solution to create the childTitle property in fooDetail interface by combining two properties from fooParent interface.

export interface fooParent {
   appId: string,
   appName: string
}

export interface fooDetail {
  childTitle: fooParent.appId + '-' + fooParent.appName
}

Any ideas on how to implement this?

childTitle: fooParent.appId + '-' + fooParent.appName

Answer №1

You have the option to utilize template literal strings:

export interface parentFoo {
    id: string,
    name: string
}

export interface detailFoo {
    title: `${parentFoo['id']} - ${parentFoo['name']}`
}

If you want to explore inference, you can refer to this illustration:

export interface parentFoo {
    id: string,
    name: string
}

export interface detailFoo {
    title: `${parentFoo['id']} - ${parentFoo['name']}`
}

const functionHandler = <
    Id extends string,
    Name extends string,
    Parent extends parentFoo & { id: Id, name: Name }
>(parent: Parent): `${Parent['id']} - ${Parent['name']}` =>
    `${parent.id} - ${parent.name}`

const outcome = functionHandler({ id: '#1', name: 'App' }) // "#1 - App"

Explore on Playground

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

Ways to transfer information from HTML form components to the Angular class

I am currently working with angular 9 and I have a requirement to connect data entered in HTML forms to the corresponding fields in my Angular class. Below is the structure of my Angular class: export interface MyData { field1: string, textArea1 ...

Step-by-step guide to setting up a TypeScript project on Ubuntu 15 using the

As a newcomer to UBUNTU, I have recently ventured into learning AngularJS2. However, when attempting to install typescript using the command: NPM install -g typescript I encountered the following error message: view image description here ...

What is the best way to encapsulate a class with generic type methods within a class that also has a generic type, but without any generic type arguments on its methods?

Below is an example of the code I am working with: class Stupid { private cache: Map<any, any> = new Map(); get<T>(key: string): T { return this.cache.get(key); }; } class Smart<T> extends Stupid { get(key: string): T { s ...

Deleting the First Item from an Array in Typescript using Angular

Clicking my Button in .html <button (click)="deleteFirst()">Delete First</button> My array setup and removal function in .ts: people = [ {first: "Tom", last: "Brown"}, {first: "Ben", last: &qu ...

What is the best way to ensure that a class instance only receives the necessary properties?

In my code, I have a function that takes in an object called DataObject and uses certain properties from it to create instances of a class. To determine which data object items should be assigned to which class properties, I use mappings in the form of a ...

Having trouble extracting a list of matches using a Regular Expression?

const stringWithDate: string = "4/7/20 This is a date!"; const reg: RegExp = new RegExp("^(\d{1,2}\/\d{1,2}\/\d{1,2})").compile(); const exist: boolean = reg.test(stringWithDate) const matches: RegExpExecArray | null = reg.exec(str ...

Error: WebStorm's Language Service has timed out while executing TSLint operations

While working on my Mac running MacOS Sierra with WebStorm (version 2017.2.4), I encounter a pop-up notification sporadically, as shown in the following image: My coworkers and I all have the same TSLint configuration and code style set up in WebStorm. Ho ...

In search of a practical and functional demonstration showcasing Electron v8 combined with TypeScript

Excuse the straightforwardness of my inquiry, as I am reaching the limits of my patience. I am in search of a practical example demonstrating the use of Electron v8 and TypeScript. The example should be simple and functional, without the need for WebPack, ...

The name '__DEV__' is not discoverable at the moment

While working with the mobx library in my project, I encountered an issue after installing it using npm. Upon exploring the mobx/src/error.ts file within the node_modules folder, I came across a compile time error on line 78: const errors: typeof niceError ...

Exploring the versatility of Vue.js through props and scoped slots

Coming from a React background, I am used to being able to easily alter children components before they render. However, after spending hours reading the VueJS documentation and searching forums, I have not been able to find a straightforward way to do thi ...

Conceal a division based on its numerical position

I'm having trouble figuring out how to hide multiple divs based on an index that I receive. The code snippet below hides only the first div with the id "medicalCard", but there could be more than one div with this id. document.getElementById("medical ...

Efficiently process and handle the responses from Promise.all for every API call, then save the retrieved data

Currently, I am passing three API calls to Promise.all. Each API call requires a separate error handler and data storage in its own corresponding object. If I pass test4 to Promise.all, how can I automatically generate its own error and store the data in ...

Is it possible to alter the name of a slot before displaying the element in the shadowDOM, depending on the slot utilized in the DOM?

In my project, I am working on implementing different features for both desktop and mobile devices. Some of these features can be replaced by slots. My goal is to have a slot that can be either replaced by a desktop slot called poster-foreground, or a mobi ...

Develop a wrapper for a function with multiple variations in TypeScript

Encountering an issue with the code below while attempting to create a proxy for a function with multiple overloads: // The target function function original (a: number): boolean; function original (a: string): boolean; function original (a: boolean): bool ...

Issue when calling .create() method on Mongoose schema: "this expression is not callable" error in TypeScript

Encountering an error with the .create method on a mongoose model in Next JS while making a call in an API route. The get request is functioning properly... The structure: pages>API>task.tsx import dbConnect from "../../util/dbconnect"; im ...

Building state from multiple child components in Next.js/React: Best Practices

To better illustrate this concept, I suggest checking out this codesandbox link. This is a follow-up to my previous question on Stack Overflow, which can provide additional context. Currently, when interacting with the child elements (such as inputs), th ...

What is the method for assigning 'selective-input' to a form field in Angular?

I am using Angular and have a form input field that is meant to be filled with numbers only. Is there a way to prevent any characters other than numbers from being entered into the form? I want the form to behave as if only integer keys on the keyboard ar ...

"Observed Issue: Ionic2 Array Fails to Update in HTML Display

I am struggling with updating an array in Ionic2 and Angular2. I have tried updating it on the front end but it's not working, even though it updates perfectly on the backend (ts) as confirmed by checking the console. I need assistance with this. Her ...

Tips on retrieving enum values in typescript

Having trouble retrieving values from an enum? Check out this snippet of code: export const enum ComplianceType { ENGINEER_ASSESMENT = 'ENGINEER_ASSESMENT', CONSTRUCTION_COMPLIANCE = 'CONSTRUCTION_COMPLIANCE', ARCHITECTURE_ASSIGN ...

"Loop through an array using forEach leads to a subscription that

I am a beginner in Angular and struggling to understand how async functions work. I have written the following code, but I am encountering an error: GET https://localhost:44353/api/ecams/id/undefined 400 and ["The value 'undefined' is not va ...