Home > OS >  Custom extension method in typescript
Custom extension method in typescript

Time:06-25

Well I was trying to create an extension method for my interface Student

declare global {  
  interface Student {  
   CourseOpted(): String;  
  }  
 }  

 Student.prototype.CourseOpted = function(): string {  
  return 'some-string';
 }  
 export {}; 

And when I place cursor on Student:- Getting this error

'Student' only refers to a type, but is being used as a value here. Was referring this article:- https://www.c-sharpcorner.com/article/learn-about-extension-methods-in-typescript/#:~:text=Extension-method gives you the,any data-type you want.

What I could notice is;- when we extend class for Interface like String, Number, Array..Extension method is possible. Then why not for the above example. Please help me! Solve this error

Thanks a lot in advance :)

CodePudding user response:

Student is an interface, not class you should create class and import it before making any changes. Maybe it is better just to create new class. You may also add serialization to it, if you take students data from server.

Typescript Playground Link

interface IStudent {
  id: number;
  firstName: string,
  lastName: string,
}

class Student implements IStudent {
  id: number;
  firstName: string;
  lastName: string;

  constructor(student: IStudent)
  constructor(id: number, firstName: string, lastName: string)
  constructor(idOrStudent: number | IStudent, firstName?: string, lastName?: string) {
    if (typeof idOrStudent === "object") {
      this.id = idOrStudent.id;
      this.firstName = idOrStudent.firstName;
      this.lastName = idOrStudent.lastName;
      return;
    }
    this.id = idOrStudent;
    this.firstName = firstName as string;
    this.lastName = lastName as string;
  }

  public foo() {
    return "bar";
  }
}

const student0 = new Student(0, "John", "Doe");
console.log(student0);
console.log(student0.foo());

const student1 = new Student({
  id: 1,
  firstName: "Milka",
  lastName: "Helgi"
});

console.log(student1);

CodePudding user response:

interface are a compiled time element. When you compile Typescript into Javascript it does not emit anything for an interface. The interface purely exist at compile time (to benefit typescript).

The reason why it works for String, Number, etc. because they exist at runtime.

If you want different implementation of the function

  • then why not declare Student as a class with default function implementation and allow a sub-class to override the functional implementation as and when required.

If you want a static implementation

  • then simply declare it as a static function inside the Student class
  • Related