DAY 4
0
Modern Web

# Introduction

## Boolean

``````let isDone: boolean = false;
``````

## Number

• 十六進制
• 十進制
• 八進制
• binary
``````let decimal: number = 6;
let hex: number = 0xf00d;
let binary: number = 0b1010;
let octal: number = 0o744;
``````

## String

``````let color: string = "blue";
color = 'red';
``````

``````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`;
``````

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

## Array

`TypeString` 和 Javascirpt依樣允許你使用 Array， 宣告時使用 `[]` 來做類型宣告

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

## Tuple

`Tuple` 允許你宣告每一個參數的類型

``````let x : [string, number];

x = ['hello', 10]; //OK
x = [10, 'hello']; //Error
``````

``````let x : [string, number];

x = ['hello', 10];
console.log(x[0].substr(1)); // OK
console.log(x[1].substr(1)); // Error, 'number' does not have 'substr'
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

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

``````enum Color {
Red = 1,
Green,
Blue
}
let colorName: string = Color[2];

console.log(colorName);
// Green
``````

``````enum Color {
Red = 1,
Green = 2,
Blue = 4
}
let colorName: string = Color[4];

console.log(colorName);
// Blue
``````

## Any

``````let notSure: any = 4;
notSure = "maybe a string instead";
notSure = false;
``````

`any` 類型相當的彈性

``````let notSuer: any = 4;
notSure.ifItExists();
notSure.toFixed();

let prettySure: object = 4;
prettySure.toFixed(); //Error: 'toFixed' not exist on type 'Object'
``````

## Void

`void` 有一點像 `any`

``````function warnUser():void{
alert('This is my warning message');
}
``````

``````let unsable: void = undefined;
``````

## Null 和 Undefined

`TypeScript``undefined``null` 有他的類型就叫做 `undefined``null`

``````let u: undefined = undefined;
let n: null = null;
``````

``````let notSure: string | null | undefined;
``````

## Never

`never` 類型代表永遠不會發生

`````` function error(message: string): never{
throw new Error(message);
}

function fail(){
return error("Something failed");
}

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

TypeScript 初學之路11