Skip to content

Commit

Permalink
类型细化与布尔值的比较
Browse files Browse the repository at this point in the history
  • Loading branch information
zhongsp committed Dec 5, 2023
1 parent 448703d commit 766d55a
Showing 1 changed file with 47 additions and 15 deletions.
62 changes: 47 additions & 15 deletions zh/release-notes/typescript-5.3.md
Original file line number Diff line number Diff line change
Expand Up @@ -102,22 +102,54 @@ TypeScript 5.3 会针对 `switch (true)` 里的每一个 `case` 条件进行类

```ts
function f(x: unknown) {
switch (true) {
case typeof x === "string":
// 'x' is a 'string' here
console.log(x.toUpperCase());
// falls through...

case Array.isArray(x):
// 'x' is a 'string | any[]' here.
console.log(x.length);
// falls through...

default:
// 'x' is 'unknown' here.
// ...
}
switch (true) {
case typeof x === 'string':
// 'x' is a 'string' here
console.log(x.toUpperCase());
// falls through...

case Array.isArray(x):
// 'x' is a 'string | any[]' here.
console.log(x.length);
// falls through...

default:
// 'x' is 'unknown' here.
// ...
}
}
```

感谢 Mateusz Burzyński 的[贡献](https://github.com/microsoft/TypeScript/pull/55991)

## 类型细化与布尔值的比较

有时,您可能会发现自己在条件语句中直接与 `true``false` 进行比较。
通常情况下,这些比较是不必要的,但您可能出于风格上的考虑或为了避免 JavaScript 中真值相关的某些问题而偏好这样做。
不过,之前 TypeScript 在进行类型细化时并不识别这样的形式。

TypeScript 5.3 在类型细化时可以理解这类表达式。

```ts
interface A {
a: string;
}

interface B {
b: string;
}

type MyType = A | B;

function isA(x: MyType): x is A {
return "a" in x;
}

function someFn(x: MyType) {
if (isA(x) === true) {
console.log(x.a); // works!
}
}
```

感谢 Mateusz Burzyński 的 [PR](https://github.com/microsoft/TypeScript/pull/53681)

0 comments on commit 766d55a

Please sign in to comment.