TypeScript Basics: Type Keyword
Welcome to the Type Keyword lesson!
This lesson is shown as static text below. However, it's designed to be used interactively. Click the button below to start!
We can declare our own names for types using the
typekeyword. It looks similar to declaring a variable withlet. By convention, user-defined type names are UpperCamelCased.>
type MyStringType = string;let s: MyStringType = 'hello';s;Result:
'hello'
>
type MyStringType = string;let s: MyStringType = 5;s;Result:
type error: Type 'number' is not assignable to type 'string'.
We can assign a
stringto aMyStringTypeand vice-versa. Think ofMyStringTypeas a new name forstring, rather than a whole new type.>
type MyStringType = string;let s1: string = 'hello';let s2: MyStringType = s1;s2;Result:
'hello'
Each TypeScript program is a valid JavaScript program, but with extra annotations: the types. After checking types, the TypeScript compiler generates JavaScript by removing all TypeScript-specific syntax from a program. Then, the result is run as JavaScript.
The declaration
type MyNumberType = numberonly contains TypeScript syntax. There's no JavaScript there! After the TypeScript compiler runs, we're left with an empty JavaScript program. Our system then runs that empty JavaScript, which gives usundefined.>
type MyNumberType = number;Result:
undefined
The particulars of our system aren't important to you, of course. But the fact that the TypeScript compiler throws the types away is important. Most notably, it means that there's no way to inspect types at runtime. Types are only used during type checking, then they're thrown away.
The technical term for this is "type erasure": the types are used for type checking, then erased from the compiled output.