0

I am new to typescript and not that familiar.

I was reading this blog on web and trying to comprehend the code

Here the author have created a simple route

// /lib/routes/crmRoutes.ts

import {Request, Response} from "express";

export class Routes {
    public routes(app): void {
        app.route('/')
        .get((req: Request, res: Response) => {
            res.status(200).send({
                message: 'GET request successfulll!!!!'
            })
        })
    }
}

Which is he is using like this in a kind of main-entry point file

// /lib/app.ts

import * as express from "express";
import * as bodyParser from "body-parser";
import { Routes } from "./routes/crmRoutes";

class App {

    public app: express.Application;
    public routePrv: Routes = new Routes();

    constructor() {
        this.app = express();
        this.config();
        this.routePrv.routes(this.app);
    }

    private config(): void{
        this.app.use(bodyParser.json());
        this.app.use(bodyParser.urlencoded({ extended: false }));
    }
}

From the definition I read on web, Classes are also like interface in typescript, so this line

 public routePrv: Routes = new Routes(); 

Here, Routes is an interface for routePrv:? And from my vague understanding, interface usually looks like this

interface Person {
  name: string;
  age: number;
} 

So my question is that, How can a class be an interface and how will our interface look like in case of

public routePrv: Routes = new Routes();

Can someone please explain the same?

4
  • A class defines a type, yes, but not an interface afaik. Commented Jul 16, 2019 at 21:00
  • @Bergi what does this mean here routePrv: Routes Commented Jul 16, 2019 at 21:09
  • It declares the routePrv property to have the type Routes Commented Jul 16, 2019 at 21:14
  • 1
    routePrv is of type Routes. Classes, interfaces and type literals are all types. Classes are the only type that emits code in the form of a function for es5 and class for es6+. An interface is only an abstract contract, i.e. it cannot contain method implementations whereas a class can. Commented Jul 16, 2019 at 21:14

1 Answer 1

1

You are confusing Interfaces and Types.

An Interface (interface MyInterface {}) is used to express what an Object has to look like. After typescript transpilation, interfaces are removed. They are more like "hints" for typescript. An example of its usage is this:

interface MyInterface {
   myProp:number;
}

const myConst = {myProp: 0}; // implicitly implements MyInterface
const myConst2:MyInterface = {myProp: 0}; // Explicitly tells typescript the type of "myConst2" should be "MyInterface"
const myConst2:MyInterface = {}; // Error, does not implement "MyInterface" correctly

function myFunc(input:MyInterface) {/* Do something */}

myFunc(myConst); // Works
myFunc(myConst2); // Works
myFunc({}); // Fails

Classes (class MyClass {}) boil down to Constructor Functions. They are a way of constructing an Object. Since they describe how to construct an Object and thus describe the constructed Object's shape, they can also be used to describe the type of an Object. Since Classes are Constructor Functions, they do something during runtime. Hence, only their usages as types are removed.

// You can explicitly implement the interface or explicitly, doesn't matter for its usage.
// Explicitly just tells typescript that this class MUST implement the interface
class MyClass /* implements MyInterface */ {
   constructor(public myProp?:number = 0) {}
} 

const myClassConst = new MyClass(); // works
const myClassConst2:MyClass = new MyClass(); // works
const myClassConst3:MyInterface = new MyClass(); // works

myFunc(myClassConst); // works
myFunc(myClassConst2); // works
myFunc(myClassConst3); // works

function myFunc2(input:MyClass) { /* Do something */ }

myFunc2(myClassConst); // works
myFunc2(myClassConst2); // works
myFunc2(myClassConst3); // works

As per Request, another example of what does not work:

class MyOtherClass {
    constructor(public myProp:number) {}
}

const myOthClassConst = new MyOtherClass(); // works
const myOthClassConst2:MyClass = new MyOtherClass(); // fails, type mismatch
const myOthClassConst3:MyInterface = new MyOtherClass(); // fails, type mismatch

function myFunc3(input:MyOtherClass) {}

myFunc3(myOthClassConst2); // works
myFunc3(myClassConst); // fails, type mismatch 

Edit: Rephrased the explanation due to ambigious meaning (thanks to @Bergi for pointing that out).

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

7 Comments

"Since they describe how to construct an Object, they can also be used to describe the type of an Object." - how it is constructed (initialised) is not so important. What matters is what shape the object has (which properties) and what methods are available on it.
@Bergi and pascalpuetz: Just to confirm, ` public routePrv: Routes = new Routes();` this will only increase readability? besides that it does not have any advantage?
@anny123 That depends on what part of the statement you mean. :Routes tells typescript that the variable MUST be of type Routes. So it prevents you from assigning anything to it that is not of type Routes. new Routes constructs a new Object (advantages if doing that are explained in pretty much every Object Oriented Programming tutorial/book).
@Bergi That's what I tried to express - as in "if you know how it's created, you also know its final shape". Thanks for pointing out the ambigious meaning.
@pascalpuetz Thanks a lot for sticking, can you please also include in your example what won't work? and why?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.