类的定义

class person {
  public gender?:number // 可选属性定义
  constructor(public name:string){

  }

  sayHello(){
    console.log('hello',this.name)
  }
}

// 接口和类定义
interface Person{
    name: string,
    gender?: number
}

class person1 implements Person{
    constructor(public name:string){

    }
}

属性修饰符

JS属性修饰符

publicprivateprotected

TS属性修饰符

publicprivateprotectedreadonly

方法的修饰符

publicprivateprotected

类的属性拦截器

class Person {
    private _gender: number
    constructor(gender: number) {
        this._gender = gender
    }

    get gender() { // getter 访问器
        return this._gender === 0 ? "男" : "女"
    }

    set gender(gender:string){ // setter 设置器
        this._gender = gender === "男" ? 0 : 1
    }
}

const p = new Person(1)
console.log(p.gender) // 女
p.gender = "男"
console.log(p.gender) // 男

泛型

TS中的一种特性,定义函数、接口或者类的时候

function getany<T>(arg: T): T {
    return arg;
}

getany<number>(1);
let s = getany('hello');   // 通过自动推导为字符串类型
getany(true);      // 通过自动推导为布尔类型

// 箭头函数定义泛型
const getany1 = <T>(arg: T): T => {
    return arg;
}

// 接口泛型
interface A<T>{
    name: T;
}

// 接口泛型的	使用
let obj:A<string> = {
    name: 'hello'
}

// 类中定义泛型
class B<T> {
    name: T;
}

const b = new B<string>();

泛型约束

interface Hashlength {
    length: number;
}

function getLength<T extends Hashlength>(arg: T): number {
    return arg.length;
}

getLength('hello world')
getLength(1) // 报错,因为数字没有length属性

泛型默认值

interface Hashlength {
    length: number;
}

function getLength<T extends Hashlength = string>(arg: T): number { // 设置泛型类型默认值为 string 类型
    return arg.length;
}

getLength('hello world')