2

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);
  }

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

-1

you can not create instance of Interface instead you can do following

let selectItem :SelectItem; 
selectItem.value = "";
selectItem.label = "Please Select";

selectItemList.push(selectItem);

4 Comments

This will crash since selectItem is undefined with a message similar to cannot set value of undefined
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.
This didn't work @RanjeetAvghad. Gave error in selectItem.value="" row. In above, Andrew 's solution worked.
@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.