Skip to content

Commit

Permalink
1111
Browse files Browse the repository at this point in the history
  • Loading branch information
sumingcheng committed Dec 10, 2024
1 parent 6a58d07 commit 8f06062
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 0 deletions.
3 changes: 3 additions & 0 deletions docs/Frontend/TypeScript/10.TypeScript简介.md
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,9 @@ TypeScript 支持两大类类型:原始类型(Primitive Types)和对象类型(Ob
```typescript
let count = 0; // 推断为number类型
const name = 'TypeScript'; // 推断为string类型

// 对于 const 声明的变量,TypeScript 会进行更严格的字面量类型推断
const status = 'active'; // 推断为 'active' 字面量类型,而不是 string
```

但如果变量的类型不明确,例如一个变量的值可能是多种类型,就需要使用联合类型(Union Types):
Expand Down
8 changes: 8 additions & 0 deletions docs/Frontend/TypeScript/40.接口.md
Original file line number Diff line number Diff line change
Expand Up @@ -145,3 +145,11 @@ const square: Square = {
```

上面的代码中,`Square`接口继承了`Shape`接口,因此它具有`color`属性,并且还添加了`sideLength`属性。

### 接口可以继承多个接口

```typescript
interface Button extends Shape, Clickable {
label: string;
}
```
22 changes: 22 additions & 0 deletions docs/Frontend/TypeScript/90.高级类型.md
Original file line number Diff line number Diff line change
Expand Up @@ -142,3 +142,25 @@ function doStuff(q: A | B) {
```

上面的例子中,`'x' in q`可以判断`q`是否为`A`类型。在`if`分支中,TypeScript 会将`q`的类型收窄为`A`,这样我们就可以放心地使用它的`x`属性了。

## 可辨识联合类型

interface Square {
kind: "square";
size: number;
}

interface Rectangle {
kind: "rectangle";
width: number;
height: number;
}

type Shape = Square | Rectangle;

function area(s: Shape) {
switch (s.kind) {
case "square": return s.size _ s.size;
case "rectangle": return s.width _ s.height;
}
}

0 comments on commit 8f06062

Please sign in to comment.