iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 3
3
Modern Web

TypeScript + React + 雜七雜八系列 第 3

【Day 03】TypeScript 基本型別介紹

話說昨天的文章裡有提到要打包成最後的 production,就先擱著等這些 TypeScript 基礎的篇章結束後再來實作。


今天要非常粗略且不專業的介紹 TypeScript 的基本型別,各位可以利用昨天建好的專案來試著故意把值改成不同型別的值,看看 TypeScript 檢查型別的威力。

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' };

有時引入第三方函式庫還無法掌握正確的型別時可能會用到,筆者認為 any 的型別宣告通常是萬不得已的情況時才適合用

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

add(2, 3);

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

add(2);

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 們常會用到


以上就是筆者常用到的寫法,是不是會有人注意到了,完全沒有任何一點 class 的影子呢?沒錯!我完全沒有使用 class,筆者正巧學 React Hooks 跟 TypeScript 是同時進行的,學著寫著就發現完全不需要用到 class,所以這邊就完全沒提到,繼續往下看下去就會知道為什麼了!


明天要將 React 給裝起來,以及非常重要的 ESLint,為了再更嚴格的規範 codeing style。


上一篇
【Day 02】從一個空白資料夾開始,建置單純編譯 .ts 的 webpack 環境
下一篇
【Day 04】引入 React + ESLint
系列文
TypeScript + React + 雜七雜八30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言