一、构造签名
class Person {
}
interface ICTORPerson {
new (): Person
}
function factory(fn: ICTORPerson) {
const f = new fn()
return f
}
factory(Person)
二、默认参数
1、函数的参数可以有默认值,有默认值的情况下,参数的类型注解可以省略
2、有默认值的参数,是可以接收一个undefined的值
三、剩余参数
function foo(...args: (string | number)[]) {
}
四、重载签名
1、编写重载签名
function add(arg1: number, arg2: number): number
function add(arg1: string, arg2: string): string
2、编写通用的函数实现
function add(arg1: any, arg2: any): any {
return arg1 + arg2
}
五、this
1、对象中的函数中的this
const obj = {
name: "abc",
studying: function(this: {}) {
console.log(this, "studying")
}
}
2、普通函数
function foo(this: {name: string}, info: {name: string}) {
console.log(this, info)
}
六、this的内置工具
1、ThisParameterType: 获取this类型
function foo(this: {name: string}, info: {name: string}) {
console.log(this, info)
}
type FooType = typeof foo
type FooThisType = ThisParameterType<FooType>
2、OmitThisParameter: 删除this参数类型,剩余的函数类型
type PureFooType = OmitThisParameter<FooType>
3、thisType: 绑定一个上下文的this
interface IState {
name: string
age: number
}
interface IStore {
state: IState
eating: () => void
running: () => void
}
const store: IStore & ThisType<IState> = {
state: {
name: "myName",
age: 21
},
eating: function() {
console.log(this.name)
},
running: function() {
console.log(this.name)
}
}
store.eating.call(store.state)
七、TS类的使用
1、类的初始化
class Person {
name: string
age: number
constructor(name: string, age: number) {
this.name = name
this.age = age
}
eating() {
console.log(this.name + "eating")
}
running() {
console.log(this.name + "running")
}
}
const p1 = new Person("name1",21)
2、类的修饰符
public 公有属性 默认
private 私有属性 类内部才能访问
protected 受保护属性 在类自身或子类中可见
class Person {
name: string
private age: number
constructor(name: string, age: number) {
this.name = name
this.age = age
}
private eating() {
console.log(this.age)
}
}
class Student extends Person {
constructor(name: string, age: number) {
super(name, age)
}
running() {
console.log(this.name)
}
}