TypeScript Types

Any

  • Every untyped variable whose type cannot be inferred, becomes implicitly any type.
  • Any is a wild card type
  • "top type"
  • Implicit any typings are usually considered problematic
    • TypeScript not used properly
    • programmer forgot to assign type
  • why the configuration rule noImplicitAny is recommended at all time

Never

  • "bottom type"
  • it will never work - can not happen
  • have problem pushing anything into an array of never[]

Tuples

  • structured set of data - comes with convention
  • an array of fixed length
  • example array of address
let bb: [number, string, string, number] = [
123,
"Fake Street",
"Nowhere
]
  • great way to return a set of data from function
  • set and retrieve - not meant for updating - becareful in how we use tuples
    • set is typed checked all at once - correct usage
    • can not safely type push function - not to use array methods on tuples
  • tuple values often require type annotations - need to be specific

Object Types

  • all properties are required

  • use optional operator (?)

  • use @ts-check to check for type errors in your JavaScript

    // @ts-check
import { Bear } from './bear.model';
const bear = new Bear(3);
if (bear instanceof Bear) {
console.log("Hello from TypeScript");
}

Return Types

import { Person } from './person.model';
function add(val1: number, val2: number): number {
return val1 + val2;
}
function sayHello(person: Person): string {
return `Say Hello to My Little Friend, ${person.firstName}!`
}
function voidExample(): void {
add(1,2);
}
function neverExample(): never {
}

to review

  • generic types