Professional Documents
Culture Documents
Classes in TypeScript
Classes in TypeScript
Classes in TypeScript
Behind the class keyword
In TypeScript, the class keyword provides a more familiar syntax for generating
constructor functions and performing simple inheritance. It has roughly the same
syntax as the ES2015 class syntax, but with a few key distinctions. Most notably, it
allows for non-method properties, similar to this Stage 3 proposal. In fact, declaration
of each instance method or property that will be used by the class is mandatory, as
this will be used to build up a type for the value of this within the class.
But what if we couldn’t use the class keyword for some reason? How would we
make an equivalent structure? Is it even possible? To answer these questions, let’s
start with a basic example of a TypeScript class:
class Point {
static fromOtherPoint(point: Point): Point {
// ...
}
x: number;
y: number;
constructor(x: number, y: number) {
// ...
}
toString(): string {
// ...
}
}
This archetypical class includes a static method, instance properties, and instance
methods. When creating a new instance of this type, we’d call new Point(<number>,
<number>), and when referring to an instance of this type, we’d use the type Point.
But how does this work? Aren’t the Point type and the Point constructor the same
thing? Actually, no!
In TypeScript, types are overlaid onto JavaScript code through an entirely separate
type system, rather than becoming part of the JavaScript code itself. This means
that an interface (“type”) in TypeScript can—and often does—use the same
identifier name as a variable in JavaScript without introducing a name conflict.
(The only time that an identifier in the type system refers to a name within
JavaScript is when the typeof operator is used.)
In other words, the example class above is effectively just shorthand for this code:
// our TypeScript `Point` type
interface Point {
x: number;
y: number;
toString(): string;
}
// our JavaScript `Point` variable, with a constructor type
let Point: {
new (x: number, y: number): Point;
prototype: Point;
// static class properties and methods are actually part
// of the constructor type!
fromOtherPoint(point: Point): Point;
};
// `Function` does not fulfill the defined type so
// it needs to be cast to <any>
Point = <any> function (this: Point, x: number, y: number): void {
// ...
};
// static properties/methods go on the JavaScript variable...
Point.fromOtherPoint = function (point: Point): Point {
// ...
};
// instance properties/methods go on the prototype
Point.prototype.toString = function (): string {
// ...
};
Now, instead of having an anonymous object type dirtying up our code, we have a
specific WidgetProperties interface that can be referenced by our code as well
as any other code that imports Widget. This means that we can easily subclass
our kwArgs parameter while keeping everything DRY and well-organized:
As mentioned earlier, using this pattern, we can also reference these types from
other code by importing the interfaces where they are needed:
import Widget, { WidgetProperties } from './Widget';
import TextInput from './TextInput';
export function createWidget<
T extends Widget = Widget,
K extends WidgetProperties = WidgetProperties
>(Ctor: { new (...args: any[]): T; }, kwArgs: K): T {
return new Ctor(kwArgs);
}
// w has type `Widget`
const w = createWidget(Widget, { style: { backroundColor: 'red' } });
// t has type `TextInput`
const t = createWidget(TextInput, { style: { backgroundColor: 'green' }
});
Access Modifiers
Another welcome addition to classes in TypeScript are access modifiers that allow
the developer to declare methods and properties as public, private, protected,
and readonly.
class Widget {
class: string; // No modifier implies public
private _id: string;
readonly id: string; /
protected foo() {
// ...
}
}
Decorators
Please note that decorators were added to TypeScript early and are only available
with the –experimentalDecorators flag because they do not reflect the
current state of the TC39 proposal. A decorator is a function that allows shorthand
in-line modification of classes, properties, methods, and parameters. A method
decorator receives 3 parameters:
The decorator function can optionally return a property descriptor to install on the
target object.
function myDecorator(target, key, descriptor) {
}
class MyClass{
@myDecorator
myMethod() {}
}