Define Mandantory Datatype for Arrays in Typescript

I want to define a jsonArray and also the datatypes, which have to be used.

My first approach was this one hear:

felder = [{
    elementId: string,  // elementId: ''  would work
    value: string,
    inputType: string
  }];

  constructor() {
    this.felder.push({elementId: 'ID1', value: 'First', inputType: 'input'});
    this.felder.push({elementId: 'ID2', value: 'Second', inputType: 'dropdown'});
    this.felder.push({elementId: 'ID3', value: 'Third', inputType: 'checkbox'});
  }

But it does not work. The error message is:

string' only refers to a type, but is being used as a value here.

I understand the error but cannot find a solution. How can I define a must-used datatype?

Thanks & Best Regards

1

1 Answer

Use an interface:

interface MyInterface {
  elementId: string;
  value: string;
  inputType: string;
}

class MyClass {
  public felder: MyInterface[] = [];

  constructor() {
    this.felder.push({elementId: 'ID1', value: 'First', inputType: 'input'});
    this.felder.push({elementId: 'ID2', value: 'Second', inputType: 'dropdown'});
    this.felder.push({elementId: 'ID3', value: 'Third', inputType: 'checkbox'});
  }
}
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Chloe Bennett

Chloe Bennett

Culture, Media & Entertainment Columnist

Chloe Bennett explores the intersection of pop culture, streaming entertainment, digital trends, and contemporary lifestyle. Her weekly commentary reaches thousands of culture enthusiasts.

Share this article
Twitter Facebook Pinterest