[Typescript] Class - Param properties
For the following class:
class Car {
make: string
model: string
year: number
constructor(make: string, model: string, year: number) {
this.make = make
this.model = model
this.year = year
}
}
We can write like this:
class Car {
constructor(
public make: string,
public model: string,
public year: number
) {}
}
const myCar = new Car("Honda", "Accord", 2017)
The first argument passed to the constructor should be a
string
, and should be available within the scope of the constructor asmake
. This also creates apublic
class field onCar
calledmake
and pass it the value that was given to the constructor
It is important to understand the order in which “constructor-stuff” runs.
class Base {}
class Car extends Base {
foo = console.log("class field initializer")
constructor(public make: string) {
super()
console.log("custom constructor stuff")
}
}
const c = new Car("honda")
The order of execution:
"use strict";
class Base {
}
class Car extends Base {
constructor(make) {
super();
this.make = make;
this.foo = console.log("class field initializer");
console.log("custom constructor stuff");
}
}
const c = new Car("honda");
Note the following order of what ends up in the class constructor:
super()
- param property initialization
- other class field initialization
- anything else that was in your constructor after
super()
Before V4.6, the follow code is not possible:
class Base {}
class Car extends Base {
foo = console.log("class field initializer")
constructor(public make: string) {
console.log("before super")
super()
console.log("custom constructor stuff")
}
}
const c = new Car("honda")
A 'super' call must be the first statement in the constructor when a class contains initialized properties, parameter properties, or private identifiers.
To fix it:
class Base {}
class Car extends Base {
private make: string;
constructor(make: string) {
console.log("before super")
super()
this.make = make;
console.log("custom constructor stuff")
}
}
const c = new Car("honda")
But after Typescript v4.6, it is possible to have some other code before super() call.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2018-08-01 [Mini Programe] Upload Images
2018-08-01 [JavaEE] Data Validation
2016-08-01 [React Native] Build a Github Repositories component
2014-08-01 [Backbone]5. Model & View, toggle between Models and Views -- 2
2014-08-01 [Backbone]4. Model & View, toggle between Model and View. -- 1
2014-08-01 [Backbone]3. More detail on View
2014-08-01 [Backbone]2. More detail in Models