Moving Types
TypeScript's type system is extremely powerful and allows moving and slicing types in ways not possible in any other single language out there.
This is because TypeScript is designed to allow you to work seamlessly with a highly dynamic language like JavaScript. Here we cover a few tricks for moving types around in TypeScript.
Key motivation for these : You change one thing and everything else just updates automatically and you get nice errors if something is going to break, like a well designed constraint system.
Copying both the Type + Value
If you want to move a class around, you might be tempted to do the following:
This is an error because var
only copied the Foo
into the variable declaration space and you therefore cannot use Bar
as a type annotation. The proper way is to use the import
keyword. Note that you can only use the import
keyword in such a way if you are using namespaces or modules (more on these later):
This import
trick only works for things that are both type and variable.
Capturing the type of a variable
You can actually use a variable in a type annotation using the typeof
operator. This allows you to tell the compiler that one variable is the same type as another. Here is an example to demonstrate this:
Capturing the type of a class member
Similar to capturing the type of a variable, you just declare a variable purely for type capturing purposes:
Capturing the type of magic strings
Lots of JavaScript libraries and frameworks work off of raw JavaScript strings. You can use const
variables to capture their type e.g.
In this example bar
has the literal type "Hello World"
. We cover this more in the literal type section.
Capturing Key Names
The keyof
operator lets you capture the key names of a type. E.g. you can use it to capture the key names of a variable by first grabbing its type using typeof
:
This allows you to have stuff like string enums + constants quite easily, as you just saw in the above example.
Last updated