Skip to content

Commit a660b60

Browse files
committed
Update dependencies, add class example
1 parent 911bb80 commit a660b60

File tree

4 files changed

+1094
-612
lines changed

4 files changed

+1094
-612
lines changed

README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,9 @@ A properly configured Visual Studio Code shows the following:
5353
![ex-1-start](doc/ex-1-start.png)
5454

5555

56+
## TypeScript References
57+
58+
If you need to look something up, the [TypeScript Handbook](https://www.typescriptlang.org/v2/docs/handbook/basic-types.html) is a great reference. Note that there are separate pages for different topics.
5659

5760
### Potential issues
5861

exercises/exercise-1/exercise.test.ts

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -296,6 +296,49 @@ test("supersets and structural compatibility", () => {
296296
type _t2 = AssertAssignable<FlavoredFoodItem, FoodItem>;
297297
});
298298

299+
test("classes", () => {
300+
class Point {
301+
constructor(public readonly x: number, public readonly y: number) {}
302+
303+
toString() {
304+
return `(${this.x}, ${this.y})`
305+
}
306+
}
307+
308+
// A class gives us a runtime object we can use to construct points with the new keyword
309+
const origin = new Point(0,0);
310+
expect(origin.x).toEqual(0);
311+
expect(origin.y).toEqual(0);
312+
expect(origin.toString()).toEqual("(0, 0)")
313+
314+
// We can also do a runtime test to see if an object was constructed with Point
315+
expect(origin instanceof Point).toBeTruthy()
316+
317+
// TypeScript also gives us a type that describes the shape of valid Point instances.
318+
// This type does not require object be constructed with the class, only that they're
319+
// structurally compatible, just like in the example above.
320+
const aPointLikeThing: Point = {
321+
x: 1,
322+
y: 1,
323+
toString: () => "(1,1)"
324+
}
325+
// As you'd expect, TypeScript isn't happy if you try to claim incompatible objects are Point.
326+
const aNotPointLikeThing: Point = {
327+
// typings:expect-error
328+
x: '1',
329+
y: 1,
330+
// typings:expect-error
331+
toString: () => null
332+
}
333+
334+
335+
// But things that are valid Point are not necessarily instances of the class.
336+
// The type and the runtime machinery are separate in TypeScript!
337+
expect(aPointLikeThing instanceof Point).toBeFalsy()
338+
339+
});
340+
341+
299342
/** 🚨 WHEN YOU UNCOMMENT THESE TESTS: 🚨
300343
* To uncomment a single test, uncomment from one star-line to the next.
301344
* Have `npm run exercise-1` running in your terminal. When you uncomment

0 commit comments

Comments
 (0)