TypeScript Notes

Ref

Basic Types

Boolean

let isDone: boolean = false

Number

1
2
3
4
let decimal: number = 6;
let hex: number = 0xf00d;
let binary: number = 0b1010;
let octal: number = 0o744;

String

Just like JavaScript, TypeScript also uses double quotes (“) or single quotes (‘) to surround string data.

1
2
let color:string = "blue"
color = 'red'

Template: Surrounded by the backtick/backquote (`) character, and embedded expressions are of the form ${ expr }.

1
2
3
4
let fullName: string = `Bob Bobbington`;
let age: number = 37;
let sentence: string = `Hello, my name is ${ fullName }.
I'll be ${ age + 1 } years old next month.`;

Equals to:

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

Array

  • Use the type of the elements followed by [] to denote an array of that element type

    let list: number[] = [1, 2, 3];

  • The second way uses a generic array type, Array:

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

Tuple

1
2
3
4
5
6
// Declare a tuple type
let x: [string, number];
// Initialize it
x = ["hello", 10]; // OK
// Initialize it incorrectly
x = [10, "hello"]; // Error

Access element with index:

1
2
console.log(x[0].substr(1)); // OK
console.log(x[1].substr(1)); // Error, 'number' does not have 'substr'

When accessing an element outside the set of known indices, a union type is used instead:

1
2
3
4
5
x[3] = "world"; // OK, 'string' can be assigned to 'string | number'

console.log(x[5].toString()); // OK, 'string' and 'number' both have 'toString'

x[6] = true; // Error, 'boolean' isn't 'string | number'

Enum

1
2
enum Color {Red, Green, Blue}
let c: Color = Color.Green;

By default, enums begin numbering their members starting at 0. You can change this by manually setting the value of one of its members. For example, we can start the previous example at 1 instead of 0:

1
2
enum Color {Red = 1, Green, Blue}
let c: Color = Color.Green;

Manually set all the values in the enum:

1
2
enum Color {Red = 1, Green = 2, Blue = 4}
let c: Color = Color.Green;

Any

1
2
3
let notSure: any = 4;
notSure = "maybe a string instead";
notSure = false; // okay, definitely a boolean

The any type is a powerful way to work with existing JavaScript, allowing you to gradually opt-in and opt-out of type-checking during compilation. You might expect Object to play a similar role, as it does in other languages. But variables of type Object only allow you to assign any value to them - you can’t call arbitrary methods on them, even ones that actually exist:

1
2
3
4
5
6
let notSure: any = 4;
notSure.ifItExists(); // okay, ifItExists might exist at runtime
notSure.toFixed(); // okay, toFixed exists (but the compiler doesn't check)

let prettySure: Object = 4;
prettySure.toFixed(); // Error: Property 'toFixed' doesn't exist on type 'Object'.

The any type is also handy if you know some part of the type, but perhaps not all of it. For example, you may have an array but the array has a mix of different types:

1
2
3
let list: any[] = [1, true, "free"];

list[1] = 100;

Void

void is a little like the opposite of any: the absence of having any type at all. You may commonly see this as the return type of functions that do not return a value:

1
2
3
function warnUser(): void {
alert("This is my warning message");
}

Declaring variables of type void is not useful because you can only assign undefined or null to them:

let unusable: void = undefined;

Null and Undefined

By default null and undefined are subtypes of all other types. That means you can assign null and undefined to something like number.

However, when using the --strictNullChecks flag, null and undefined are only assignable to void and their respective types. This helps avoid many common errors. In cases where you want to pass in either a string or null or undefined, you can use the union type string | null | undefined. Once again, more on union types later on.

As a note: we encourage the use of --strictNullChecks when possible, but for the purposes of this handbook, we will assume it is turned off.

Never

The never type represents the type of values that never occur.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// Function returning never must have unreachable end point
function error(message: string): never {
throw new Error(message);
}

// Inferred return type is never
function fail() {
return error("Something failed");
}

// Function returning never must have unreachable end point
function infiniteLoop(): never {
while (true) {
}
}

Type assertions

Type assertions have two forms.

  • One is the “angle-bracket” syntax:

    1
    2
    3
    let someValue: any = "this is a string";

    let strLength: number = (<string>someValue).length;
  • The other is the as -syntax:

    1
    2
    3
    let someValue: any = "this is a string";

    let strLength: number = (someValue as string).length;

When using TypeScript with JSX, only as -style assertions are allowed.

Variable Declarations

Interfaces

Classes

Functions

Generics

Enums

Type Inference

Type Compatibility

Advanced Types

Symbols

Iterators and Generators

Modules

Namespaces

Namespaces and Modules

Module Resolution

Declaration Merging

JSX

Decorators

Mixins

Triple-Slash Directives

Type Checking JavaScript Files

坚持原创技术分享,您的支持将鼓励我继续创作!