Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to duplicate my Entity Framework classes in Typescript when using Angular 2?

Let's say I have a nice C# backend with Entity Framework. I've got my database set up and a simple class like

public class MyItem
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int ItemID { get; set; }
    public string ItemName { get; set; }
}

I've got a nice Angular2 front end where I retrieve data from an API and present such as...

template: '<div>{{ItemName}} - {{ItemID}}</div>'

At the moment I have a duplicate, seemingly redundant typescript class ie

export class MyItem{
  ItemID: number;
  ItemName: string;
}

Is there any way I can avoid this typescript class? Can I bind to an object that isn't defined in advance? In Angular 1 we could bind to any property on the scope {{MyItem.SomeProperty}}

like image 218
Vok Avatar asked Nov 01 '25 02:11

Vok


1 Answers

In my project I've used TypeLite. It can generate TypeScript interfaces based on your C# classes. Worked just fine. If you change smth on you backend you'll see errors in your client code without running you app. If you don't need type safety on the client side, you can use any as was said already.

E.g. Next C# class:

public class Person {
    public string Name { get; set; }
    public List<address> Addresses { get; set; }
}

will be converted to

interface Person {
    Name: string;
    Addresses: Address[];
}

Also you can use next tools/extensions:

  • TypescriptSyntaxPaste
  • TypeWriter - one more powerfull extension for VS.
like image 112
Artiom Avatar answered Nov 03 '25 18:11

Artiom



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!