2

In Typescript,

When I want to create model class, I have two options. Either I create an Interface with properties or I create a Class with public variables.

Both of them will work. Only difference I can see is that in class i can provide default values.

Then which approach is better here ?

1
  • 1
    Class and interface are two different concepts. TypeScript enhanced the meaning of interface but they are still different things that cannot be interchanged. Commented May 17, 2019 at 5:38

6 Answers 6

2

Model classes that tend to be just bags of properties is an anti-pattern. It is better to encapsulate data along with logic that operates on that data (behavior) inside same construct. Hence, class is a better option.

For instance, if a model class has an Email property it is better to validate the email format inside the model class's setter method.

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

Comments

1

Depends, is it a type of data, is it a data, interface is kind of like contract. Is it going to have any sort of logic? Like let's say is it going to build a full name based on first name and last name, will it have other sort of logic? If those are required you need to have a class.

But if those are just types of data, and specially coming from an API, then you don't even need to initialize it, they should be interface. Same as if you're going to send this data over the wire as request, then it should be an interface.

Comments

1

Let's put it this way.

Your TypeScript code will be finally transpiled to some JavaScript code.

A TypeScript interface is just a contract - it simply defines what properties and functions the object of this interface can have.
It's a compile-time thing and it does not affect the result JavaScript code you get from your TypeScript code.

A class is a concrete thing - and it will be converted to some JavaScript code (either a function with prototype definition or to a modern ES6 class) on transpiling.

So, if you just need a structure for your data and that's all, use an interface, it will not add any overhead to your program.

But if you need to add some logic to your model class (for example, to make a validation on assigning Email property as mentioned in one of the other answers), then use a class.

2 Comments

Definition is ok, but doesn't answer the question from OP.
Added a conclusion to my answer.
0

It really depends on your implementation, if you are simply using it as a data structure I would suggest an interface as this allows casting from network requests or creation through JSON object where this is not possible if you have implemented a class. Something like this:

const myModel: MyModelInterface = {
    key: 'value',
    key: 'value'
}

or

async function getData(){
    const response = await fetch('http://myurl.com');
    const result = await response.json();
    const castResult = result as MyModelInterface;
}

A class, however, is a complex data structure that utilises constructors and can have method implementations so if you have some methods that should be attached to your data structure a class would be the way to go. Something like this:

class Model {
    value: number;

    constructor(value: number) {
        this.value = value;
    }

    increment(): void {
        this.value++;
    }
}

const model = new Model(0);
model.increment()

This article might be of use for further information

Comments

0

The answer below does apply to any language that uses interfaces.

So an interface defines behaviour from a domain point of view, so you might want to think of it as an abstraction layer that filters out the details not required and ties up the usage to model behaviours and not instance or class type, example:

You have a very business heavy logic class that takes a request to process ticketing for a commute from location A to B.

You need to model (create class) a **car**, the current domain (understanding of usage) goes like 

“I need to know a cars occupancy and max speed because I am using it to book tickets to fill and determine time of journey.”

At this point you have an understanding that a car might be abstracted to a vehicle, you don’t need to worry about color or engine displacement or other details.

So in the future the domain can be extended to add train, airplane, boat and rickshaws (classes that implement the vehicle interface).

All you care about is the behaviour from you domain perspective which is transportation and then you get the added benefit that you don’t have a hard dependency between tickets and cars and easier testing with mocking behaviour against a the interface.

Give me the domain that you are using interfaces for so I tailor the answer to it.

Comments

0

Don't let answers that try get into Object orientated programming confuse you, in Typescript these are realistically the only differences.

Interfaces compile into zero code, chuck an interface in the typescript playground and look at the output it is zero.

Classes compile to run-time code, chuck a class in the typescript playground look at the output and it will contain all the runtime level logic in order to construct itself.

Classes and Interfaces are both types, and interfaces can be essentially used to mimic classes, however they are fundamentally different.

One is a shape. One is a shape and constructible.

(Example of interface being used to mimic classes in typescript)

interface Foo {
    new(name: string, age: number): Foo;
    age: number;
    name: string;
}

Comments

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.