TypeScript 001: Basic Types

最近开始学习TypeScript的一些随手笔记,年纪大了怕忘了。

Basic Types

  • Boolean

    1
    let isDone: boolean = false;
  • Number

    1
    let decimal: number = 6;
  • String

    1
    2
    let fullName: string = `Bob Dylan`
    let sentence: string = "Hello, my name is " + fullName + ".\n\n" + "I'll be " + (age + 1) + " years old next month."
  • Array

    1
    2
    let list: number[] = [1, 2, 3];
    let list: Array<number> = [1, 2, 3];
  • Tuple

    • array with a fixed number of elements whose types are known
    1
    let x: [string, number]    // order matters
  • Enum

    • enums begin numbering their members starting at 0
    • you can go from a numeric value to the name of that value in the enum
    1
    2
    enum Color {Red, Green, Blue}
    let c: Color = Color.Green;
    1
    2
    3
    4
    enum Color {Red = 1, Green, Blue}
    let colorName: string = Color[2]

    console.log(colorName); // Green
  • Any

    • describe the type of variables that we do not know when we are writing an application
    1
    2
    3
    let notSure: any = 4;
    notSure = "maybe a string instead"
    notSure = false;
  • Void

    • the absence of having any type at all
    1
    2
    3
    4
    function warnUser(): void {
    console.log("This is my warning message")
    }

  • Null and Undefined

    1
    2
    3
    let u: undefined = undefined;
    let n: null = null;

  • Never

    • represents the type of values that never occur
    • the return type for a function expression that always throws an exception or one that never returns
    • the never type is a subtype of every type
    • no type is a subtype of never
    1
    2
    3
    4
    function error(message: string): never {
    throw new Error(message)
    }

  • Object

    1
    2
    3
    4
    declare function create(0: object | null): void;

    create({ prop: 0 });

  • Type assertions

    1
    2
    3
    let someValue: any = "this is a string";
    let strLength: number = (<string>someValue).length

    1
    2
    3
    let someValue: any = "this is a string";
    let strLength: number = (someValue as string).length