You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
thrownewError('Unable to find DOM element #root');
366
373
}
367
374
368
375
root.addEventListener('click', e=> {
@@ -387,7 +394,7 @@ class Point {
387
394
388
395
上面示例中,属性`x`和`y`会报错,因为 TypeScript 认为它们没有初始化。
389
396
390
-
这时就可以使用非空断言,表示这两个属性肯定有值,这样就不会报错了。
397
+
这时就可以使用非空断言,表示这两个属性肯定会有值,这样就不会报错了。
391
398
392
399
```typescript
393
400
classPoint {
@@ -507,17 +514,17 @@ function assertIsDefined<T>(
507
514
const assertIsNumber = (
508
515
value:unknown
509
516
):assertsvalueisnumber=> {
510
-
if (typeofvalue!=='number')
511
-
throwError('Not a number');
517
+
if (typeofvalue!=='number')
518
+
throwError('Not a number');
512
519
};
513
520
514
521
// 写法二
515
522
typeAssertIsNumber=
516
523
(value:unknown) =>assertsvalueisnumber;
517
524
518
525
const assertIsNumber:AssertIsNumber= (value) => {
519
-
if (typeofvalue!=='number')
520
-
throwError('Not a number');
526
+
if (typeofvalue!=='number')
527
+
throwError('Not a number');
521
528
};
522
529
```
523
530
@@ -568,7 +575,8 @@ function loadPerson(): Person | null {
568
575
let person =loadPerson();
569
576
570
577
function assert(
571
-
condition:unknown, message:string
578
+
condition:unknown,
579
+
message:string
572
580
):assertscondition {
573
581
if (!condition) thrownewError(message);
574
582
}
@@ -585,3 +593,4 @@ console.log(person.name);
585
593
-[Const Assertions in Literal Expressions in TypeScript](https://mariusschulz.com/blog/const-assertions-in-literal-expressions-in-typescript), Marius Schulz
586
594
-[Assertion Functions in TypeScript](https://mariusschulz.com/blog/assertion-functions-in-typescript), Marius Schulz
587
595
-[Assertion functions in TypeScript](https://blog.logrocket.com/assertion-functions-typescript/), Matteo Di Pirro
0 commit comments