Exploring Typescript: Inheritance within Interfaces

Just dipped my toes into the world of TypeScript and I'm curious about the best approach to handle this scenario.

I've got some JSON data coming from an API, like so:

{"name" : "A Person", "age": "25", createdAt: "timestamp"}

And I've defined an interface IPersonData to represent this incoming JSON.

export interface IPersonData {
  name: string;
  createdAt: string;
  age: string;
}

However, I also have an actual Person Object within the system:

export interface IPerson extends IPersonData {
  createdAt: DateTime; //this is the luxon DateTime
  age: number;
}

While Webstorm seems fine with this (it even provides an icon indicating it's overridden), the compiler isn't happy, throwing the error message:

Type 'DateTime' is not assignable to type 'string'.

I even attempted the following workaround:

 export interface IPerson extends Omit<IPersonData, "createdAt">{
  createdAt: DateTime; //this is the luxon DateTime
  age: number;
}

Is it possible to override in TypeScript? If not, would it be worth representing the incoming JSON to ensure consistency with the JSON leaving the API?

Answer №1

Your final code snippet is almost there, but you may have encountered the following error message:

Interface 'IPerson' incorrectly extends interface 'Omit<IPersonData, "createdAt">'.
  Types of property 'age' are incompatible.
    Type 'number' is not assignable to type 'string'.(2430)

It's important to note that the error is not related to the createdAt field. Since you are changing the data type of age from a string to a number, you also need to omit it.

An interesting fact is that with Omit, you can omit multiple fields by providing a union of strings.

export interface IPerson extends Omit<IPersonData, 'createdAt' | 'age'> {
  createdAt: DateTime;
  age: number;
}

This modification achieves the desired outcome.

Interactive Code 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

Issue with redirecting to another link in Angular routing

After numerous attempts, I finally managed to configure the adviceRouterModule correctly. Despite extensive research and Google searches, I couldn't quite crack it. Here is the configuration for my AdviceRoutingModule: const adviceRouters: Routes = ...

Creating a TypeScript custom type checker for checking the length of strings

I'm currently developing a React component that requires a string prop to have a maximum length of 10 characters. My goal is for the compiler to trigger an error whenever a user attempts to pass a string longer than 10 characters. interface Componen ...

The message "Missing property 'type' in type 'typeof WithXXX'" indicates an error

Currently, I am working on a project using React in combination with Typescript. My goal is to create a higher order component based on the react-dnd library. The problem arises within the DragSource section of the react-dnd component. Here is the relevant ...

Harnessing the power of the map function in TypeScript

Here is a collection of objects: let pages = [{'Home': ['example 1', 'example 2', 'example 3']}, {'Services': ['example 1', 'example 2', 'example 3']}, {'Technologies&apos ...

DiscoverField Component with Button Functionality and Checkbox Dilemma

I'm working with Vue 3, Vuetify, and TypeScript for my searchField component. Inside, I have two buttons: FreeItemMaster and PatternMaster. Clicking on these buttons should change their background color and display respective content below them. Howev ...

What is the process for obtaining the result of an asynchronous function triggered by an event in HTML?

I am currently working on an Angular application where I have a button that triggers a click event. The method being called is asynchronous and involves subscribing to an observable. My goal is to call player.start() only after the listItems.getData() meth ...

Utilizing Cordova Plugins in Angular 2 Mobile Apps: A Guide

Spent hours searching with no luck on how to integrate a Cordova plugin into my Angular2 app. Can anyone offer guidance on how to do this successfully? And once the plugin is included, how can I access its methods? ...

Is there a way I can replace this for loop with the array.some function?

I am looking to update the filterOutEmails function in the following class to use array.some instead of the current code. export class UsertableComponent { dataSource: MatTableDataSource<TrialUser> createTableFromServer = (data: TrialUsers[], ...

Exploring ways to use TypeScript to export a Mongoose model?

There's a module I need to export in order to avoid the error "OverwriteModelError: Cannot overwrite Task model once compiled". I've tried various solutions but none seem to work. The problem lies in the last line (export default models...) impo ...

Utilizing closure to implement a counting mechanism within a function

Every time I attempt this, it only displays once and seems to be incorrect. Is there a way to resolve the issue? function myFunc() { var increment = (function() { var i = 0; return function() { i++; ...

Issue with rendering images retrieved from JSON data

Struggling with displaying images in my Ionic and Angular pokedex app. The JSON file data service pulls the image paths, but only displays the file path instead of the actual image. Any ideas on what might be causing this issue? Sample snippet from the JS ...

Issues with NPM start arise moments after incorporating create react app typescript into the project

I've encountered an error while trying to initiate my create react app with Typescript. Despite following all the necessary steps, including adding the .env file (with SKIP_PREFLIGHT_CHECK=true) and updating/reinstalling NPM, I keep facing this issue. ...

Error Alert: The function split cannot be applied to params[item]

ERROR! The console is outputting a message stating that TypeError: params[item].split is not a function. I would greatly appreciate any assistance in resolving this issue. Understanding where I went wrong in tackling this problem would be the most benefici ...

The specified object '[object Object]' is not compatible with NgFor, which only supports binding to iterable data types like Arrays

I have some code that is attempting to access objects within objects in a template. <table class="table table-striped"> <tr *ngFor="let response of response"> <td><b>ID</b><br>{{ response.us ...

Generating automatic generic types in Typescript without needing to explicitly declare the type

In the scenario where I have an interface containing two functions - one that returns a value, and another that uses the type of that value in the same interface - generics were initially used. However, every time a new object was created, the type had to ...

Is there a way to view the type signature of the resulting intersection type (type C = A & B) in IDE hints, rather than just seeing the components?

When analyzing types defined by intersection in Typescript, I notice that the hint remains identical to the original definition: https://i.stack.imgur.com/mjvI8.png However, what I actually want is to visualize the resulting shape, similar to this: http ...

Dependency injection in Angular 2 pipes

Greetings everyone! I'm a newcomer to angular 2 and currently trying my hand at creating a custom pipe/filter. However, I've encountered an issue when attempting to inject the pipe I created inside app.ts as shown in the image linked here. Here ...

The Angular Tooltip feature is unable to interpret the characters "' '" or "' '"

Let me explain the scenario: I am receiving a list of objects from my back-end service, which I then break apart using ngFor and display accordingly. Each item in the list has an associated toolTip that provides additional information. The info for each i ...

Issues with getOptionLabel in Material UI

I have a constant with the following values : const Reference = [ { label: "RF-100", year: "Test" }, { label: "RF-200", year: "Test2" }, { label: "RF-300", year: "Test3" }, ]; and my Autoco ...

Angular material snackbar overlaps FAB button upon appearing

In my Redux action, I make an API call and trigger a toast using a custom service when the call is successful. The toast ends up covering a FAB that I have displayed. I am currently looking for a way to detect when the snackbar (toast) opens and closes so ...