Appending an item to an array in TypeScript

I'm feeling lost. I'm attempting to insert new objects into an array in TypeScript, but I encountered an error. My interface includes a function, and I'm puzzled. Can anyone offer guidance?

interface Videos{
    title: string;
    description: string;
    like: number;
    pressLike():void;
    pressDislike():void;
}
    
class Video implements Videos{
    public title: string;
    public description: string;
    public like: number;

    constructor(title: string, description: string, like?: number){
        this.title = title;
        this.description = description;
        this.like = like || 0;
    }

    public pressLike():void{
        let ins_like = this.like;
        if(ins_like < 0){
            this.like = 0;
        }else{
            this.like++;
        }
    }

    public pressDislike():void{
        let ins_like = this.like;
        if(ins_like < 0){
            this.like = 0;
        }else{
            this.like--;
        }
    }
}

var videoArr: Videos[] = [
    {"title": "Book 1 Water", "description": "Learn the water bending", "like": 0}
];
    
    // The error occurs here when trying to add new videos to the array

The error mentions missing pressLike and pressDisplike properties, even though they are functions. How can I include them in the array?

Answer №1

If you need to work with JSON data in your TypeScript code, you can define static methods for parsing the JSON and creating new instances based on the data:

interface Movie {
  title: string;
  genre: string;
  rating: number;
}

class NetflixMovie implements Movie {
  public title: string;
  public genre: string;
  public rating: number;

  constructor(title: string, genre: string, rating?: number) {
    this.title = title;
    this.genre = genre;
    this.rating = rating ?? 0;
  }

  public addToList(): void { /** ... */ }

  public removeFromList(): void { /** ... */ }

  static parse(data: string): NetflixMovie {
    const parsed: Record<string, object> = JSON.parse(data);
    const title: string = parsed.title as unknown as string;
    const genre: string = parsed.genre as unknown as string;
    const rating: number = parsed.rating as unknown as number;
    return new NetflixMovie(title, genre, rating);
  }

  static fromObject(data: Movie): NetflixMovie {
    return new NetflixMovie(data.title, data.genre, data.rating);
  }
}
const movieList: Movie[] = [
  // Constructor
  new NetflixMovie("Movie 1", "Action"),

  // From an object
  NetflixMovie.fromObject({
   title: "Movie 2",
   genre: "Comedy",
   rating: 0,
 }),

  // Parsed from JSON data
  NetflixMovie.parse(`
  {
  "title": "Movie 3",
   "genre": "Drama",
  "rating": 0
}
  `),
];

console.log(movieList);

Answer №2

When adding an object to an array, it is important to specify the object's type.

For example:

interface Customer {
  id: number;
  name: string;
  email: string;
}

const customers: Customer[] = [];

const newCustomer: Customer = {
  id: 1,
  name: 'Sarah',
  email: 'sarah@example.com'
};

customers.push(newCustomer);

Answer №3

If you want to keep things simple and just make use of what you already have (your constructor), you can do the following:

var videoArr: Videos[] = [
    new Video("Book 1 Water", "Learn the water bending", 0),
    new Video("Book 2 Earth", "Sokka in the jungle", 4)
];

When you have at least one class of the supertype (in this case, Video), the type of your array (: Videos[]) can be inferred automatically, simplifying the declaration to just var videoArr = [ ... ]. Many modern IDEs such as Webstorm/Jetbrains and VSCode can also provide a preview of the parameter names alongside your constructor parameters. Lastly, it's worth considering the difference between using var and let.

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

I successfully merged two arrays (decks of cards) without using recursion, but I'm curious to understand where I went wrong with the recursive approach

Currently, I am working on a function that shuffles two arrays together using recursion. The goal is to combine the top and bottom halves of a deck of cards into a single array with elements interleaved. For example: The first element should come from the ...

Understanding the contrast between a put request subscription with an arrow versus without in Typescript

I'm sorry if the title is not very clear. In my Angular project, I have come across two different put requests: public Save() { const types: string[] = this.getTypes.getCurrentTypes(); this.userTypeService .updateTypes(this.userID, gro ...

Having difficulty creating a TypeScript function

I've encountered a TypeScript error that has left me puzzled: src/helpers.ts:11:14 - error TS2322: There's an issue with this piece of code and I can't quite grasp it: Type '<T extends "horizontal" | "vertical" | undefined, U extends ...

Incorporate Canvg version 4 into a TypeScript project

I am currently facing an issue with an older TypeScript project that has the following tsconfig setup: { "compilerOptions": { "baseUrl": "./src", "outDir": "build/dist", "module": &q ...

Steps for incorporating a new element in Reactjs

While attempting to insert a new element into a React object, I encountered the following issue: const isAdmin = true let schema = { fname: Yup.string().required('Required'), lname: Yup.string().required('Required&apo ...

Guide on replacing empty values, marked as "", at the corresponding index with values from a separate array

In need of help with two string arrays that have the same size, but different values: arrayAlpha = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"] ...

Unable to utilize the web-assembly Rust implementation due to the error stating 'Cannot access '__wbindgen_throw' before initialization'

Looking to integrate some web-assembly into my project, I started off by testing if my webpack setup was functioning properly and able to utilize my .wasm modules. Here's a snippet of what I came up with: #[wasm_bindgen] pub fn return_char() -> cha ...

Changing the default route in Angular 2 based on conditions

I'm currently developing an application where, upon entering the page, the default route for the user is the "Login" page. However, I want to implement a condition based on whether the user has a local storage variable (id) set. If this variable exist ...

Delete a particular item from a JSON object in real-time using TypeScript/JavaScript

Upon examining the JSON data provided, it contains a node called careerLevels which includes inner child elements. input = { "careerLevelGroups": [ { "201801": 58, "201802": 74, ...

Guidelines for forming a composite type with elements?

Imagine having a convenient function that wraps a generic component with a specified constant. function wrapComponent(ComponentVariant: ComponentVariantType) { return ( <Wrapper> <ComponentVariant> <InnerComponent /> ...

Achieving CommonJS imports compilation with Typescript

In my TS file, I've included a 3rd party package using import XXX { YYY, ABC, 123 } from 'XXX'; While it compiles to CommonJS without any issues, I'd prefer to have it compiled to an ESModule instead. I tried changing the target and mo ...

Is there a way to implement hover behavior for a Material-UI Button within a ButtonGroup component?

When using MUI v5, I am encountering an issue where the first button in the code provided is only half working. The button is initially colored red (both the border and text), however, upon hovering over it, the color of the border changes to blue. This is ...

Dispatch a gentle reminder email to students and administrators

My code is supposed to send emails to learners, but I'm encountering an error: "Fatal error: Call to undefined method mysqli_result::fetch() in /home/train4/public_html/hocotest/cron-email-expire-1.php on line 46" I replaced fetch(PDO::FETCH_OBJ) wi ...

Utilize React to display a Selected button within a whitespace

Currently, I am encountering an issue in React where I have a group of buttons at the bottom. Upon selecting a button, the corresponding text should display at the top within a specified whitespace. However, I am looking to have the whitespace already occu ...

What is the best way to utilize v-model with an array of strings in a Vuex store when using v-for

Encountered an issue while trying to set a value in an Array within the Vuex Store: VueCompilerError: v-model cannot be used on v-for or v-slot scope variables because they are not writable. Seeking alternatives to achieve this without creating a local co ...

In React, the edit mode fails to display class attributes

When I attempted to combine both the creation and editing functionalities in one form, I encountered a problem. Specifically, I was able to retrieve the correct ID value when editing an element, but I struggled to access the attribute values. import { yup ...

Issue with CORS when starting SAM local API

I have encountered a CORS issue while using AWS CDK (Typescript) and running SAM local start-api to launch an API connected to lambda resolvers. The problem arises when attempting to access the API from a web browser. Below is the code snippet causing the ...

Determining interface value based on the presence of another optional interface value

I am working with an interface that looks like this: export interface IButton { label: string; withIcon?: boolean; underlined?: boolean; selected?: boolean; iconName?: string; isLink?: boolean; href?: string; onCLick?: () => void; } My question ...

Angular version 12 (node:3224) UnhandledPromiseRejectionWarning: Issue encountered with mapping:

Trying to generate the translation file in my Angular project using the command ng extract-i18n --output-path src/translate, I encountered this error message: \ Generating browser application bundles (phase: building)...(node:3224) UnhandledPromiseRej ...

Navbar Username in Next.js with Typescript and Supabase Integration

I'm currently facing an issue with retrieving the username of a user to display in my navbar. The desired username is stored in the "username" column of the table called "profiles" in my Supabase database. However, the data that's populating the ...