函数类型的表达式
函数作为参数是也可以标识类型
type Calcfunc= (number1:number,number2:number)=>number
接受两个参数的函数,number1 为number 类型,number2为number类型,返回值为number类型 使用
function foo(fn: Calcfunc){ |
调用签名
函数表达式不支持声明属性 需要声明属性采用调用签名
interface IcalcFun { |
构造签名
JS 函数也可以使用 new 操作符调用,当被调用的时候,TS 会认为这是一个构造函数(constructors),因为 他们会产生一个新对象。
class person { |
参数的可选类型
标识符前面:
加 ?
表示可选类型,表示一个联合类型 类型| undefined
// age 表示可选 number | undefined |
默认参数
从ES6开始,JavaScript是支持默认参数的,TypeScript也是支持默认参数的
// y 默认参数为 6 |
剩余参数
从ES6开始,JavaScript也支持剩余参数,剩余参数语法允许我们将一个不定数量的参数放到一个数组中
function foo(...nums: number[]){ |
函数的重载
编写一个add函数,可以对字符串和数字类型进行相加
- 在TS中,我们可以去编写不同的重载签名(overload signatures)来表示函数可以以不同的方式进行调用
- 一般是编写两个或者以上的重载签名,再去编写一个通用的函数以及实现
function add(x1: number, x2: number): number |
重载和联合两种实现方案都可行
在可能的情况下,尽量选择使用联合类型来实现
指定this类型
有关 JS this coderwhy大佬有文章讲解 链接
function foo(this: { name: string}){ |
- 函数的第一个参数我们可以根据该函数之后被调用的情况,用于声明
this的类型
(名词必须叫this) - 在后续调用函数传入参数时,从第二个参数开始传递的,
this参数
会在编译后被抹除
this相关的内置工具
Typescript 提供了一些工具类型来辅助进行常见的类型转换,这些类型全局可用
- ThisParameterType
- 用于提取一个函数类型Type的this (opens new window)参数类型
- 如果没有返回 unknown
type ThisType = ThisParameterType<typeof 函数名称>
- OmitThisParameter
- 用于移除一个函数类型Type的this参数类型, 并且返回当前的函数类型
type ThisType = OmitParameterType<typeof 函数名称>
- ThisType
- 标记一个上下文的this类型
// 接口
interface IState {
name: string
age: number
}
interface IData {
state: IState
running: ()=>void
eating: ()=>void
}
// 把 IState 类型标记成 info的上下文this类型
const info:IData & ThisType<IState> ={
state: {name: 'fantasy', age: 18 }
running: function() {
console.log(this.name)
},
eating: function(){
// ...
}
}
info.running.call(info.state)