函数
函数的类型就是描述函数入参类型与函数返回值类型
。
函数的类型签名
const foo1 = function( name:stirng ) :number {
return name.length
}
const foo2: (name:string) => number = function (name) {
return name.length
}
//箭头函数
const foo3 =( name:string ): number => {
return name.length
}
// 不建议这样写
const foo:(name:string)=> number =( name ) => {
return name.length
}
可选参数与 rest 参数
参数有默认值
,就是可选参数
。
重载
在某些逻辑较复杂的情况下,函数可能有多组入参类型和返回值类型
:
// 未使用重载 返回值一直是个联合类型
function set(a:number,b?:string): string | number {
if(b){
return String(a)
}else{
return a *100
}
}
const a = set(1) // string | number
const b = set(1,"2") // string | number
可以这样改写:
function set(a:number,b:string):string
function set(a:number):number
function set(a:number,b?:string): string | number {
if(b){
return String(a)
}else{
return a *100
}
}
const a = set(1) // number
const b = set(1,"2") // string
Class
关注构造函数、属性、方法和访问符
。
Class简介(非ts内容)
class Point{
constructor(x,y){
this.x = x;
this.y = y;
}
toString(){
return "x:" + this.x + "y:" + this.y
}
}
typeof Point // "function"
Point === Point.prototype.constructor //true
- 类的数据类型就是函数
- 类本身就指向构造函数(constructor)
- 类的所有方法都定义在类的
prototype
属性上面 - 在类的实例上面调用方法,其实就是调用原型上的方法。
静态方法
类相当于实例的原型,所有在类中定义的方法,都会被实例继承。如果在一个方法前,加上static
关键字,就表示该方法不会被实例继承,而是直接通过类来调用,这就称为“静态方法”。
class Foo {
static classMethod(){
return "hello"
}
}
Foo.classMethod() // "hello"
// 实例不能调用class里的静态方法
const foo = new Foo();
foo.classMethod(); // TypeError: foo.classMethod is not a function
// 父类的静态方法可以被子类继承 同时子类内部也可以通过super字段调用。
class Bar1 extends Foo{
}
Bar1.classMethod() // 'hello'
class Bar2 extends Foo {
static classMethod() {
return super.classMethod() + ', too';
}
}
Bar2.classMethod() // 'hello too'
修饰符
- public:此类成员在类、类的实例、子类中都能被访问。
- private:此类成员仅能在类的内部被访问。
- protected:此类成员仅能在类与子类中被访问。
不显式的使用访问性修饰符,成员默认的访问性会被标记成public
。
同时,对构造函数直接使用修饰符,可以免去手动创建并赋值的步骤。
class Foo {
constructor(public arg1: string, private arg2: boolean) { }
}
new Foo("linbudu", true)
继承
基类和派生类。 基类中的方法可以被派生类覆盖掉。 override可以用来确保派生类尝试覆盖的方法一定在基类中存在定义。
抽象类
我的理解就是描述类的方法和属性。 通过implements实现:
abstract class AbsFoo {
abstract absProp: string;
abstract get absGetter(): string;
abstract absMethod(name: string): string
}
class Foo implements AbsFoo {
absProp: string = "linbudu"
get absGetter() {
return "linbudu"
}
absMethod(name: string) {
return name
}
}