Typescript Basic Syntax

Typescript Syntax Notes

basic type designation

let stringArray: string[];
// TS yells at you because stringArray was typed as a an array of strings and the inclusion of a number 3 raises an error.
stringArray = ['one', 'two', 3]

let myBoolean: boolean;

Interface

  • a way to tell typescript more information about objects to catch errors whilst writing code.

  • are used for compile checks only and have NO EFFECT on the code at runtime.

  • "Option A" below tends to be cleaner: telling typescript what type I intend the variable to be, then, have it make sure I'm assigning the right object type

// this interface describes the object shape.
interface Todo {
    name: string;
    completed: boolean;
    // putting a ? makes property optional
    // typescript will not raise error if omitted
    cost?: number
}

// OPTION A
const myTodo: Todo = {
    name: 'buy tacos',
    completed: false,
    cost: 32
    // any attempt to add additional properties
    // or assign an incorrect type to name, will throw an error.
}

// OPTION B
// alternatively, could use the 'casting' syntax
// here, instead of defining the type of variable as 'Todo',
// we instead cast the object assigned to the variable
// to the Todo via <Todo>
const myTodoCastSyntax = <Todo> {
    name: 'exercise',
    completed: true
  }

// we can create an interface for methods as well, like if we
// want to implement CRUD functionality on a Todo.   
interface ITodoService {
  // expects no arguments and returns an array of Todo objects
  getAll(): Todo[];
  // expects one argument, Todo id, and returns a single Todo object. \
  getById(id: number): Todo;
  // this function doesn't return anything (as it would likely
  // execute an AJAX call upon invocation).
  deleteById(id: number): void;
  // takes in a Todo and returns a newly created Todo object
  addTodo(todo: Todo): Todo;
}

// enum example

interface Thing {
    name: string;
    status: ThingState;
}

enum ThingState {
    New = 1,
    Active = 2,
    Complete = 3,
    Deleted = 4,
}

const myThing: Thing = {
    name: 'thing one',
    status: ThingState.New,
}

function delete(anyThing: Thing) {
    if(thing.status != ThingState.Complete ) {
        throw " can't delete incomplete task"
    }
}

The basics

                    // A                                      // B
function totalLength(x: (string | any[]), y: (string | any[])): number {
            // C
  const total: number = x.length + y.length;

  // D
  if(x instanceof Array ) {
    x.push('abc')
  }
  // D
  if(x instanceof String) {
    x.substr(1)
  }

  return total
}

Figure 1

A) TELLS TYPESCRIPT that the first argument, x, can be a String OR and Array of 'anything' (meaning, the array can contain entries of any type). The parenthesis around the 'UNION TYPE' syntax are optional, and included only for clarity.

B) TELLS TYPESCRIPT that the function totalLength() should return a Number.

C) TELLS TYPESCRIPT that the constant 'total' within the function block should be a Number.

D) TYPEGUARD SYNTAX, in cases where an argument can be of different types, it is used to check the argument, and, if it makes it into the if block, typescript knows it's of a certain type and lets you treat it that way (i.e. call type-specific methods, .push() for array)

Anonymous/In-line type definition

// types myVar to an object with a name property that is a string
let myVar: { name: string };

myVar = 42 // throws typescript error because 42 is NOT a string.

// can be used in place of union types.
// opens this function up to accepting any argument with a
// length property.
function totalLength(x: (length: number), y: {length: number}): number {
    const total: number = x.length + y.length;
    return total
}
arrow_back

Previous

AWS CloudFront

Next

AWS Command Line Interface
arrow_forward