This commit is contained in:
xugaoyi 2022-08-21 23:10:19 +08:00
parent a2b103c239
commit 87370e0be1
1 changed files with 100 additions and 3 deletions

View File

@ -76,6 +76,35 @@ const someValue:any = 'abc'
const strLength:number = (someValue as string).length // 断言someValue是字符串类型 const strLength:number = (someValue as string).length // 断言someValue是字符串类型
``` ```
### 类型断言
```typescript
const el = document.querySelector('#img');
(el as HTMLImageElement).src = 'xx' // 断言el就是图片元素类型
// 对象内的类型断言
type TestObj = {
a: string
};
const obj = {
test: <TestObj>{
a: 'aaa'
}
}
// 或者
const obj = {
test: {
a: 'aaa'
} as TestObj ,
}
```
### 对象的类型 ### 对象的类型
```typescript ```typescript
@ -138,7 +167,75 @@ function add({ one, two }: {one: number, two: number}) {
} }
const total = add({one: 1, two: 2}) const total = add({one: 1, two: 2})
// 类型别名方式定义函数类型
type Callback = (a: string) => string
let fn: Callback = (a) => ''
// 接口方式定义函数类型
interface ICallBack {
(a: string): string
}
let fn1: ICallBack = (a) => ''
``` ```
#### 函数中的this类型
```typescript
interface TestObj {
a: number,
fn: (x: number) => void
}
// 普通函数的this
let obj: TestObj = {
a: 1,
fn(this: TestObj, x: number){ // 注意这里的this非参数只是给this类型注解。x还是第一个参数
this.a
}
}
// 箭头函数的this (this是固定指向当前声明函数所在的作用域)
let obj2: TestObj = {
a: 1,
fn(this: TestObj, x: number) {
return () => {
this.a
}
}
}
```
#### 函数重载 (函数参数间的组合约定)
原生js中并没有真正的函数重载重名函数会被覆盖但ts中可以有。
> [浅谈JavaScript函数重载](https://www.cnblogs.com/yugege/p/5539020.html)
ts支持函数重载一般用于针对传入不同的参数或参数数量以及返回值之间的类型约定。
```typescript
// 第一套约定attr是'display'时value必须是 'block' | 'nonde'
function showOrHide(ele: HTMLElement, attr: 'display', value: 'block' | 'nonde');
// 第二套约定attr是'opacity'时value必须是number
function showOrHide(ele: HTMLElement, attr: 'opacity', value: number);
// 函数的实现
function showOrHide(ele: HTMLElement, attr: any, value: any) {
// ...
}
// interface也可以声明函数重载
interface Fn{
(name: string): string
(name: number): number
}
const fn: Fn= () =>
```
更多 [ts函数重载知识](https://zhuanlan.zhihu.com/p/496792140)