Adding an item to interface array list in Typescript

10,854

You can simply:

selectItemList.push({
  value: "",
  label: "Please Select",
});

https://www.typescriptlang.org/docs/handbook/interfaces.html

One of TypeScript’s core principles is that type-checking focuses on the shape that values have. This is sometimes called “duck typing” or “structural subtyping”. In TypeScript, interfaces fill the role of naming these types, and are a powerful way of defining contracts within your code as well as contracts with code outside of your project.

So any object that fills that contract can be considered a SelectItem. Making an instance doesn't really make sense since at runtime the interfaces are completely stripped away. They are only for 'develop time' convenience.

Share:
10,854
realist
Author by

realist

Updated on December 07, 2022

Comments

  • realist
    realist 11 months

    I have an interface with name SelectItem created automatically by primeNG like below. And i want to create an instance and add my select item array. If the SelectItem is class instead of interface, the code will be work. But now, giving an error. Please don't advice that change the type of SelectItem from interface to "class". I can't change because it is component of primeNG. How can i achieve this?

    selectitem.ts

    export interface SelectItem {
        label?: string;
        value: any;
        styleClass?: string;
        icon?: string;
        title?: string;
        disabled?: boolean;
    }
    

    my method

      addUnselectedItem(selectItemList: SelectItem[]) {
        let selectItem = new SelectItem(); //this row giving error
        selectItem.value = "";
        selectItem.label = "Please Select";
    
        selectItemList.push(selectItem);
      }
    
  • Andrei Tătar
    Andrei Tătar about 5 years
    This will crash since selectItem is undefined with a message similar to cannot set value of undefined
  • Ranjeet Avghad
    Ranjeet Avghad about 5 years
    SelectItem is an Interface and we can use it like Type of an object. why it will throw an error?. If you are talking about our variable then in typescript variables are based on Type here SelectItem and will not be undefined.
  • realist
    realist about 5 years
    This didn't work @RanjeetAvghad. Gave error in selectItem.value="" row. In above, Andrew 's solution worked.
  • Andrei Tătar
    Andrei Tătar about 5 years
    @RanjeetAvghad I was talking about the variable, not the interface. Your code in js would be similar to let selectItem; selectItem.value = '';. You need to init selectItem for it to work.