Skip to Content
Learning TypeScript
book

Learning TypeScript

by Josh Goldberg
June 2022
Beginner
320 pages
6h 40m
English
O'Reilly Media, Inc.
Book available
Content preview from Learning TypeScript

Chapter 8. Classes

Some functional devs

Try to never use classes

Too intense for me

The world of JavaScript during TypeScript’s creation and release in the early 2010s was quite different from today. Features such as arrow functions and let/const variables that would later be standardized in ES2015 were still distant hopes on the horizon. Babel was a few years away from its first commit; its predecessor tools such as Traceur that converted newer JavaScript syntax to old hadn’t achieved full mainstream adoption.

TypeScript’s early marketing and feature set were tailored to that world. In addition to its type checking, its transpiler was emphasized—with classes as a frequent example. Nowadays TypeScript’s class support is just one feature among many to support all JavaScript language features. TypeScript neither encourages nor discourages class use or any other popular JavaScript pattern.

Class Methods

TypeScript generally understands methods the same way it understands standalone functions. Parameter types default to any unless given a type or default value; calling the method requires an acceptable number of arguments; return types can generally be inferred if the function is not recursive.

This code snippet defines a Greeter class with a greet class method that takes in a single required parameter of type string:

class Greeter {
    greet(name: string) {
        console.log(`${name}, do your stuff!`);
    }
}

new Greeter().greet("Miss Frizzle"); // Ok

new Greeter().greet();
//            ~~~~~
// Error: ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Understanding TypeScript

Understanding TypeScript

Maximilian Schwarzmüller

Publisher Resources

ISBN: 9781098110321Errata PageSupplemental Content