TypeScript
# TypeScript
TypeScript is a superset of JavaScript, with all the features of JavaScript + a type checking layer.
# Why TypeScript
TypeScript helps to combat common errors:
- Uncalled Functions:
|
|
- Logic errors
|
|
# Defining Types
# Type Inference
|
|
This is in contrast to Java which types have to be explicitly defined:
|
|
# Type Aliases
A name for any type
|
|
# Type Interfaces
|
|
OOP type annotations:
|
|
__An interface is always extendable but an alias is not open for extension:
# Composing Types
# Unions
|
|
TypeScript will only allow an operation if it is valid for every member of the union. For example, if you have the union string | number
, you can’t use methods that are only available on string. Use typeof <x> === "<type>"
to check for types before calling type specific methods.
# Types with Generics
|
|
# Structural Type System
In a structural type system, if two objects have the same shape, they are considered to be of the same type.
|
|
An object need only to match all the type attributes for the code to pass (can have more but not less).
# Type Assertions
Sometimes you will have information about the type of a value that TypeScript can’t know about.
For example, if you’re using document.getElementById
, TypeScript only knows that this will return some kind of HTMLElement
, but you might know that your page will always have an HTMLCanvasElement
with a given ID.
In this situation, you can use a type assertion to specify a more specific type: const myCanvas = document.getElementById("main_canvas") as HTMLCanvasElement;
Angle-bracket syntax (except if the code is in a .tsx
file), which is equivalent: const myCanvas = <HTMLCanvasElement>document.getElementById("main_canvas");
Runtime behaviour Because type assertions are removed at compile-time, there is no runtime checking associated with a type assertion. There won’t be an exception or
null
generated if the type assertion is wrong.
TypeScript only allows type assertions which convert to a more specific or less specific version of a type. This rule prevents “impossible” coercions like: const x = "hello" as number;
This rule can be too conservative and will disallow more complex coercions that might be valid. You can use two assertions, first to any
or unknown
,then to the desired type:
const a = (expr as any) as T;
# Literal Types
The types used in the union above include some literals e.g. “locked”, 1
# Literal Inference (or lack thereof):
When you initialize a variable with an object, TypeScript assumes that the properties of that object might change values later.
req.method
must have the type string
, not "GET"
:
|
|