Normal Usage
1 | class Greeter1 { |
for name, the type annotation is optional, but will be an implicit
any
if not specified.
strictPropertyInitialization(tsconfig.json)
whether
1 | // strictPropertyInitialization = true |
readonly
1 | class Greeter { |
Constructor
- 和函数一样(支持parameter type 注释和 optional parameters 和 parameters default value)
- 支持重载
difference with function signature
Constructor 不支持 type parameter - 整个放在 class 上
Constructor 不支持 returns type annotations - 构造函数本身返回的类型即 class 本身
1 | class Greeter3<T> { |
Super Calls
when class extends base class , super must be called in constructor function .
Accessors
get/set
1 | class C { |
- 只有 get,没有 set 时 length 会变为 readonly
- type inference: get accessors returns type can infer to set parameter type, 当没有添加set 参数类型的时候。
- Member Visibility
index Signature
1 | class MyClass { |
as boolean
index signature type needs to also capture the types of methods.
Because the index signature type needs to also capture the types of methods, it’s not easy to usefully use these types. Generally it’s better to store indexed data in another place instead of on the class instance itself.
implements(实现)
- class 可以 implements interface
- class 也可以 implements class
- implements 不同于 extends,需要声明所有的useable properties,extends 则不需要。
Extends(继承)
- class extends class
- interface extends interface
Override methods
派生类 (Derived class) override的方法仍需要兼容其基类。
1 | class Base2 { |
Super Calls
通过super去调用基类的field method
declare
只做声明,不做初始化赋值,使用 declare
派生类的执行顺序
声明构造函数接口
1 | interface Person { |
Member Visibility
public
protected
private
Can’t access from outside the class
Cant access from subclass properties
一些缺陷
Cross-instance private
access
private protect 仅可在TypeScript,但在 编译后的JavaScript 仍然可以访问。
新的 ES 语法:JS通过 # 来保证私有。
Static Member
挂在class上,而不是实例
- 可以和member visibility 一起使用
1 | class S { |
不能和泛型一起使用。
this
This 取决于运行时runtime.
多用于子类, other object.
this as parameter
1 | // ts |
1 | // js |
ts 规避 this 问题
1 | class ClassA { |
this as type
This 也可以作为 type 使用。
constructor parameter turn into properties
通过在构造函数中声明的参数和type,可以被class 的实例继承。
1 | class Pencil { |