Slide 1

Slide 1 text

Busy Typescript Developer's Guide to the Typescript Type System Getting the most out of the Typescript Type System by Maina Wycliffe @mwycliffe_dev mainawycliffe.dev

Slide 2

Slide 2 text

● Javascript Superset ● Strongly Typed ● Has no runtime ● Provides Additional Tooling e.g. language server What is Typescript?

Slide 3

Slide 3 text

Types help Declare your Intentions ● Tell Typescript what are you are building ● Helps Typescript know how to Type check your code

Slide 4

Slide 4 text

Types are a set of value - Number - all possible numbers: 1,2,0, -2, 1.2, etc. - String - all possible string combinations e.g. Angular, Typescript, Foo, Bar, etc. - Boolean - True or False - Arrays - Array of numbers, string, objects, etc. - Any - could be all possible values, no restrictions

Slide 5

Slide 5 text

The same applies to unions Unions allow us to combine types Indicates a variable can have one of those types Possible values are the ones declared in the union and not anything else

Slide 6

Slide 6 text

Type Narrowing ● Move an imprecise type to a more precise types ● Improve Type Safety

Slide 7

Slide 7 text

Ways to Narrow Types Type Guards Truthiness Narrowing instanceof for Narrowing in Operator for Narrowing

Slide 8

Slide 8 text

Ways to Narrow Types Discriminated Unions ● Use a common field to narrow types ● The common field needs to be literal type ● Common use case - events types, shapes, etc.

Slide 9

Slide 9 text

Ways to Narrow Types Custom Type Guards in Typescript ● A function that returns a predicate ● A predicate takes the form parameterName is Type ● The function returns true or false ● Make sure to do an exhaustive check before returning

Slide 10

Slide 10 text

Unknown vs Any - Any overrides Type Checking - Any is used for compatibility - Unknown is for variables whose Type is unknown - Use unknown instead of Any - Unknown cannot be used without Type Narrowing

Slide 11

Slide 11 text

● Indicates that the values will never occur ● For example: The Never Type 1. A function that never returns 2. variables also acquire the type never when narrowed by any type guards that can never be true.

Slide 12

Slide 12 text

Template Literal Types in TypeScript ● Literal types allow us to define types that are more specific ● Build new types using a template just like template literal strings ● Can expand to many different string using Unions

Slide 13

Slide 13 text

Utility Types Create Types from Existing Types Partial Pick Omit Required ReadOnly

Slide 14

Slide 14 text

Generics ● Allow creation of components that are reusable across multiple components ● Avoids using of any type ● Uses Type Variable to pass the type used to the component

Slide 15

Slide 15 text

Q & A

Slide 16

Slide 16 text

Thank You Follow me on twitter: @mwycliffe_dev