7

How should I implement TypeScript interface to define this C# models:

public class PageModel
{
    public long Id { get; set; }
    public string Name { get; set; }
    public IDictionary<string, FieldModel> Fields { get; set; }
}

public class FieldModel
{
    public long Id { get; set; }
    public string Name { get; set; }
    public string Type { get; set; }
    public string DataType { get; set; }
    public string DefaultValue { get; set; }
}
monstro
  • 6,254
  • 10
  • 65
  • 111
  • 2
    Duplicate http://stackoverflow.com/questions/15877362/declare-and-initialize-a-dictionary-in-typescript – Kalten Aug 08 '16 at 15:28
  • 1
    Not a duplicate, that question is asking something different and much more specific: «Why isn't the initialization rejected? After all, the second object does not have the "lastName" property.» – ANeves Dec 11 '18 at 16:49

1 Answers1

14

If you're looking for interfaces only then:

interface PageModel {
    Id: number;
    Name: string;
    Fields: { [key: string]: FieldModel };
}

interface FieldModel {
    Id: number;
    Name: string;
    Type: string;
    DataType: string;
    DefaultValue: string;
}

Some differences:

  1. Javascript has no notion of long/integer/double, they are all numbers
  2. In a simple map implementation which is based on the js object notation, the keys are only strings. In typescript these are called Indexable Types
  3. While you get use get/set inside classes, the interfaces don't have that and you can only define the property.
Nitzan Tomer
  • 155,636
  • 47
  • 315
  • 299
  • Why use an `interface` and not a `class`? – gotnull Jun 30 '17 at 00:08
  • 1
    @fuzz If you're only looking for objects to contain data (without methods) then the javascript object is a better option than a class. You are using an interface to describe how this js object will look like. – Nitzan Tomer Jun 30 '17 at 00:53