Typescript is a very nice and pragmatic addition to Javascript, and enables a bunch of nice programming safety features that would be more difficult to implement without it. I’ve been reading the book Effective Typescript recently, and I thought I’ll start a short series on the tips and tricks I’ve picked up from it. So here’s part 1 of a 5 part series on some advanced things you can do with Typescript.
To Follow Along
Please install ts-node
and typescript
globally:
npm install ts-node typescript -g
& then just ts-node
should give you a terminal:
❯ ts-node
> 1 + 1
2
> const a = "hello"
undefined
> a
'hello'
You can use this to get a Typescript REPL & then follow-along with the rest of the examples.
typeof operator
typeof
is a Javascript construct that gives you a type of an object. If you use this in Javascript, then you get simple Javascript types:
> const a = {hello: "world"}
undefined
> typeof a
'object'
But in a type context, the same operator can be used for much richer type information:
> let b: typeof a;
undefined
> b = {hello: 1}
[eval].ts:4:6 - error TS2322: Type 'number' is not assignable to type 'string'.
4 b = {hello: 1}
~~~~~
[eval].ts:1:12
1 const a = {hello: "world"}
~~~~~~~~~~~~~~
The expected type comes from property 'hello' which is declared here on type '{ hello: string; }'
As you can see, using typeof
as a type annotation on the left side of the new variable b produced the inferred type { hello: string }
, a much more complex type than just object
and Typescript good at this kind of inference. It works for more than simple variables too:
> let isNegative = (b: number) => b < 0
undefined
> let isPositive: typeof isNegative = "hello"
[eval].ts:7:5 - error TS2322: Type '"hello"' is not assignable to type '(b: number) => boolean'.
7 let isPositive: typeof isNegative = "hello"
~~~~~~~~~~
Here we see that we can use typeof to infer the type of a function. This can be used in several different places, and even when you import values or functions from an external library that has types.
Constructing Partial Types with Pick and Omit
You can use Pick and Omit to construct subset of types pretty easily:
> let metadata = {
... isOpen: false,
... isDraft: false,
... isComplete: true
... }
undefined
> type Metadata = typeof metadata;
> type SaveMetadata = Pick<Metadata, "isOpen" | "isComplete">
Here we’re defining a new type SaveMetadata
as being derived from Metadata
but having picked up only the isOpen
and isComplete
keys. This saves duplication & makes the code a lot more DRY. Omit
is the reverse:
> type SaveMetadata = Omit<Metadata, "isDraft">
These are the same types written in two different ways.
That’s it for today! More Typescript goodness when we meet next!
Leave a Reply