typescript详解
邵预鸿 Lv5

类型断言

1
2
3
const ele = document.querySelector('#canvas') as HTMLCanvasElement

const ele = <HTMLCanvasElement>document.querySelector('#canvas')

In

1
2
3
4
5
6
7
8
type Fish = { swim: ()=>void }
type Bird = { fly: ()=>void }
function func(method: fish|Bird){
if('swim' in Fish){
Fish.swim()
}
return Bird.fly()
}

instansof

1
2
3
4
5
6
7
 function func(x: Date | string){
if(x instanceof Date){
console.log(x.getTime())
}else{
console.log('string')
}
}

带属性的函数(函数签名)

1
2
3
4
5
6
7
8
9
type IFunc = {
count: number,
(value: number): string
}

const getCount: IFunc = value=>{
return '111'
}
getCount.count = 1;

泛型

1
2
3
4
function doSomething<T>(a: T):T{
//检测T的类型,并返回T类型
}
doSomething('hello')

多种泛型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function doSomething<T extends {length:number},B>(a: T, b: T):T // 公共属性条件约束

function doSomething<T extends string|number,B>(a: T, b: B):B{
//检测T的类型, B的类型, 返回B的类型
if(typeof b === 'string'){
return b+'123' as B;
}
if(typeof b === 'number'){
return b*2 as B;
}
return b;
}

doSomething('hello', 123)
  • 本文标题:typescript详解
  • 本文作者:邵预鸿
  • 创建时间:2025-07-17 09:54:27
  • 本文链接:/images/logo.jpg2025/07/17/typescript详解/
  • 版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!