Execute Program

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 type keyword. It looks similar to declaring a variable with let. By convention, user-defined type names are UpperCamelCased.

  • >
    type MyStringType = string;
    let s: MyStringType = 'hello';
    s;
    Result:
    'hello'Pass Icon
  • >
    type MyStringType = string;
    let s: MyStringType = 5;
    s;
    Result:
    type error: Type 'number' is not assignable to type 'string'.Pass Icon
  • We can assign a string to a MyStringType and vice-versa. Think of MyStringType as a new name for string, rather than a whole new type.

  • >
    type MyStringType = string;
    let s1: string = 'hello';
    let s2: MyStringType = s1;
    s2;
    Result:
    'hello'Pass Icon
  • 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 = number only 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 us undefined.

  • >
    type MyNumberType = number;
    Result:
    undefinedPass Icon
  • 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.