DAY 3
1
Modern Web

## Boolean

``````const isCheck: boolean = true;
const isValid: boolean = false;
``````

## Number

``````const number1: number = 123;
const number2: number = 3345678;
``````

## String

``````const string1: string = '嗨你好';
const string2: string = '我是誰';
``````

## Any

``````// 宣告 any 不管是什麼型別的值都可以接受
let any: any = 'anything';
any = null;
any = 321;
any = { name: 'horse' };
``````

## void

``````const showMessage = (): void => {
console.log('warning message')
};

[1, 2, 3].forEach((n): void => console.log(n));
``````

void 最常用在要執行 Side Effect 的函數上

## Array

``````const stringArray: string[] = ['first', 'second', 'third'];

// 物件陣列
const noArray: { no: number }[] = [
{ no: 1 },
{ no: 2 },
{ no: 3 },
];
``````

## Null

``````let data: string | null = null;
data = 'something';

let app: HTMLElement | null = document.querySelector('#app');
``````

## Undefined

``````let data: string | undefined;
data = 'something';

// Array.find 回傳型別為 T | undefined
const foundNumber: number | undefined = [1, 2, 3]
.find((n): boolean => n === 1);
``````

null 或 undefined 使用情境大多都是這樣有可能空又有可能有值

## Functions

``````function add(x: number, y: number): number {
return x + y;
}

// 可選參數 y?
function add(x: number, y?: number): number {
if (y) {
return x + y;
}
return x;
}

``````

function 參數上，筆者認為最有趣的用法是直接規定可以傳進去的字串

## Interfaces

``````interface PropsI {
name: string;
}

function Component(props: PropsI): string {
const { name } = props;

return name;
}

// 如果是物件陣列
interface SomeObject {
first: string;
second: number;
}

const someObjects: SomeObject[] = [
{ first: 'haha', second: 2 },
{ first: 'hihi', second: 4 },
];
``````

## Generics

``````function typeIsUpToYou<T>(arg: T): T {
return arg;
}

const number: number = typeIsUpToYou<number>(123);

let stringOrNull: string | null = typeIsUpToYou<string | null>(null);
stringOrNull = 'string';
stringOrNull = null;
``````

React Hooks `useState<T>()` 等等的 Hooks 們常會用到