Typescript - Class

About

Classes in TypeScript are just a shorthand for the prototype-based OO

public is a shorthand that creates properties from the argument with the same name.

Example

  • a Student class with a constructor and a few public fields. public is a shorthand that creates properties from the argument with the same name. The class has then 4 properties (fullName, firstName, middleInitial and lastName)

    .

class Student {
    fullName: string;
    constructor(
        public firstName: string, 
        public middleInitial: string, 
        public lastName: string
     ) {
        this.fullName = firstName + " " + middleInitial + " " + lastName;
    }
}
  • As the Person interface share the same property names than the Student, a Student is also a Person
interface Person {
    firstName: string;
    lastName: string;
}
let user = new Student("Jane", "M.", "User");
  • And can be used in every function expecting a Person.
function greeter(person: Person) {
    return "Hello, " + person.firstName + " " + person.lastName;
}
document.body.textContent = greeter(user);





Discover More
Javascript - Typescript

TypeScript is a typed superset of JavaScript that compile to plain JavaScript. It adds static typing. JSdocReference See When...



Share this page:
Follow us:
Task Runner