Skip to content

Commit 7a099bc

Browse files
MACMAC
authored andcommitted
ts 常见类型守卫方式 样式调整
1 parent 9eadafe commit 7a099bc

File tree

1 file changed

+33
-35
lines changed

1 file changed

+33
-35
lines changed

docs/TypeScript/index.md

Lines changed: 33 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -1209,41 +1209,39 @@ console.log(arr)
12091209

12101210
### 常见类型守卫方式
12111211

1212-
1.**`typeof` 类型守卫:** 判断基本类型(`string``number``boolean`
1213-
2.**`instanceof` 类型守卫:** 判断对象是否为某个类的实例
1214-
3.**`in`操作符守卫:** 判断对象是否包含某个属性
1215-
4.**字面量类型守卫:** 用于联合类型中的字面量
1216-
1217-
```ts
1218-
1219-
type Result = { status: 'success'; data:string} | {status:'error';code:number}
1220-
1221-
function handleResult(result:Result){
1222-
if(result.status === 'success') {
1223-
console.log(result.data)
1224-
} else {
1225-
console.log(result.code)
1226-
}
1227-
}
1228-
```
1229-
1230-
5.**自定义类型守卫(类型谓词)**
1231-
1232-
通过函数返回`arg is Type` 明确类型断言:
1233-
1234-
```ts
1235-
function isString(value:unknown):value is string {
1236-
return typeof value === 'string'
1237-
}
1238-
1239-
function process(input: string | number) {
1240-
if(isString(input)) {
1241-
console.log(input.trim())
1242-
} else {
1243-
console.log(input.toFixed(2))
1244-
}
1245-
}
1246-
```
1212+
1. **`typeof` 类型守卫:** 判断基本类型(`string``number``boolean`
1213+
2. **`instanceof` 类型守卫:** 判断对象是否为某个类的实例
1214+
3. **`in`操作符守卫:** 判断对象是否包含某个属性
1215+
4. **字面量类型守卫:** 用于联合类型中的字面量
1216+
1217+
```ts
1218+
1219+
type Result = { status: 'success'; data:string} | {status:'error';code:number}
1220+
1221+
function handleResult(result:Result){
1222+
if(result.status === 'success') {
1223+
console.log(result.data)
1224+
} else {
1225+
console.log(result.code)
1226+
}
1227+
}
1228+
```
1229+
1230+
5. **自定义类型守卫(类型谓词):** 通过函数返回`arg is Type` 明确类型断言:
1231+
1232+
```ts
1233+
function isString(value:unknown):value is string {
1234+
return typeof value === 'string'
1235+
}
1236+
1237+
function process(input: string | number) {
1238+
if(isString(input)) {
1239+
console.log(input.trim())
1240+
} else {
1241+
console.log(input.toFixed(2))
1242+
}
1243+
}
1244+
```
12471245

12481246
### 类型守卫与类型断言
12491247

0 commit comments

Comments
 (0)