Skip to content

Commit

Permalink
Update dependencies, add class example
Browse files Browse the repository at this point in the history
  • Loading branch information
dcolthorp committed Apr 1, 2020
1 parent 911bb80 commit a660b60
Show file tree
Hide file tree
Showing 4 changed files with 1,094 additions and 612 deletions.
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,9 @@ A properly configured Visual Studio Code shows the following:
![ex-1-start](doc/ex-1-start.png)


## TypeScript References

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.

### Potential issues

Expand Down
43 changes: 43 additions & 0 deletions exercises/exercise-1/exercise.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -296,6 +296,49 @@ test("supersets and structural compatibility", () => {
type _t2 = AssertAssignable<FlavoredFoodItem, FoodItem>;
});

test("classes", () => {
class Point {
constructor(public readonly x: number, public readonly y: number) {}

toString() {
return `(${this.x}, ${this.y})`
}
}

// A class gives us a runtime object we can use to construct points with the new keyword
const origin = new Point(0,0);
expect(origin.x).toEqual(0);
expect(origin.y).toEqual(0);
expect(origin.toString()).toEqual("(0, 0)")

// We can also do a runtime test to see if an object was constructed with Point
expect(origin instanceof Point).toBeTruthy()

// TypeScript also gives us a type that describes the shape of valid Point instances.
// This type does not require object be constructed with the class, only that they're
// structurally compatible, just like in the example above.
const aPointLikeThing: Point = {
x: 1,
y: 1,
toString: () => "(1,1)"
}
// As you'd expect, TypeScript isn't happy if you try to claim incompatible objects are Point.
const aNotPointLikeThing: Point = {
// typings:expect-error
x: '1',
y: 1,
// typings:expect-error
toString: () => null
}


// But things that are valid Point are not necessarily instances of the class.
// The type and the runtime machinery are separate in TypeScript!
expect(aPointLikeThing instanceof Point).toBeFalsy()

});


/** 🚨 WHEN YOU UNCOMMENT THESE TESTS: 🚨
* To uncomment a single test, uncomment from one star-line to the next.
* Have `npm run exercise-1` running in your terminal. When you uncomment
Expand Down
Loading

0 comments on commit a660b60

Please sign in to comment.