diff --git a/doc/handbook/Advanced Types.md b/doc/handbook/Advanced Types.md index 710cb76..c95e5c7 100644 --- a/doc/handbook/Advanced Types.md +++ b/doc/handbook/Advanced Types.md @@ -14,15 +14,15 @@ function extend(first: First, second: Second): First & Second { const result: Partial = {}; for (const prop in first) { if (first.hasOwnProperty(prop)) { - (result)[prop] = first[prop]; + (result as First)[prop] = first[prop]; } } for (const prop in second) { if (second.hasOwnProperty(prop)) { - (result)[prop] = second[prop]; + (result as Second)[prop] = second[prop]; } } - return result; + return result as First & Second; } class Person { @@ -151,11 +151,10 @@ else if (pet.fly) { ```ts let pet = getSmallPet(); -if ((pet).swim) { - (pet).swim(); -} -else { - (pet).fly(); +if ((pet as Fish).swim) { + (pet as Fish).swim(); +} else if ((pet as Bird).fly) { + (pet as Bird).fly(); } ``` @@ -170,7 +169,7 @@ TypeScript里的*类型守卫*机制让它成为了现实。 ```ts function isFish(pet: Fish | Bird): pet is Fish { - return (pet).swim !== undefined; + return (pet as Fish).swim !== undefined; } ``` diff --git a/doc/handbook/Interfaces.md b/doc/handbook/Interfaces.md index 17f83ad..fff97ed 100644 --- a/doc/handbook/Interfaces.md +++ b/doc/handbook/Interfaces.md @@ -453,7 +453,7 @@ interface Square extends Shape { sideLength: number; } -let square = {}; +let square = {} as Square; square.color = "blue"; square.sideLength = 10; ``` @@ -473,7 +473,7 @@ interface Square extends Shape, PenStroke { sideLength: number; } -let square = {}; +let square = {} as Square; square.color = "blue"; square.sideLength = 10; square.penWidth = 5.0; @@ -494,7 +494,7 @@ interface Counter { } function getCounter(): Counter { - let counter = function (start: number): string { return '' }; + let counter = (function (start: number) { }) as Counter; counter.interval = 123; counter.reset = function () { }; return counter; diff --git a/doc/handbook/Type Compatibility.md b/doc/handbook/Type Compatibility.md index 9ee987b..4d1644c 100644 --- a/doc/handbook/Type Compatibility.md +++ b/doc/handbook/Type Compatibility.md @@ -128,8 +128,8 @@ function listenEvent(eventType: EventType, handler: (n: Event) => void) { listenEvent(EventType.Mouse, (e: MouseEvent) => console.log(e.x + ',' + e.y)); // Undesirable alternatives in presence of soundness -listenEvent(EventType.Mouse, (e: Event) => console.log((e).x + ',' + (e).y)); -listenEvent(EventType.Mouse, <(e: Event) => void>((e: MouseEvent) => console.log(e.x + ',' + e.y))); +listenEvent(EventType.Mouse, (e: Event) => console.log((e as MouseEvent).x + "," + (e as MouseEvent).y)); +listenEvent(EventType.Mouse, ((e: MouseEvent) => console.log(e.x + "," + e.y)) as (e: Event) => void); // Still disallowed (clear error). Type safety enforced for wholly incompatible types listenEvent(EventType.Mouse, (e: number) => console.log(e));