let userName: string; // 將變數用 : 宣告型別
userName = 'Sharon';
let userAge: number = 18; // 直接賦值
選填 ?: 非必填
const person: { name: string, age: number, address?: string } = {
    name = 'Sharon',
    age = 18,
};
const color: string[] = ['red', 'blue', 'pink'];
const luckyNumber: number[] = [13, 7, 9, 0];
跟上面相同
const luckyNumber: Array<number> = [13, 7, 9, 0];
const luckyItem: (string | number)[] = [1, 3, 5, 'S'];
const luckyItem: Array<string | number> = [1, 3, 5, 'S'];
const add = (x: number, y: number ): number => {
    return x + y;
}
add(3, 8)
const add = ({ x, y }: {x: number, y: number}): number => {
    return x + y;
}
const add = ({ x, y }: { x: number, y: number}): void => {
    console.log(x + y);
}
const add = (x: number, y: number): never => {
  throw new Error('This is never');
};
add(3, 5);
let foo: undefined;
let bar: null;
let occupation: 'Programmer'; -> 強制是某值(?)
occupation = 'Programmer';
literal type[3],可以是字串或數值,並且經常會搭配聯集(|)來使用:
這時候 brand 這個變數的值就只能是這三個字串中的其中一種,否則都會報錯。
let brand: 'iphone' | 'samsung' | 'sony';
在開發者沒有主動定義變數型別的情況下,TypeScript 會自動去對變數進行型別推論,並以此作為該變數的型別
const greet = 'Hello TypeScript';
// 因為使用 const 時,TS 會推論它為一個 literal type
let greet = 'Hello TypeScript';
// 則會推論是 string,所以之後值改變了,也只能是 string
const book1: {
    name: string,
    price: number,
} = {
    name: 'book1',
    price: 99,
};
const book2: {
    name: string,
    price: number,
} = {
    name: 'book2',
    price: 999,
};
type Book = {
  name: string;
  price: number;
};
// 在 : 後放入的是命名過的型別
const book1: Book = {
  name: 'Learn TypeScript',
  price: 300,
};
type Book = {
  author: string;
  publishedAt: string;
};
type Device = {
  brand: string;
  releasedAt: string;
};
type Product = Book | Device;
// book 這個變數符合 Product Type,
// 因為只要符合 Book Type 或 Device Type 其中之一即可符合 Product Type
const book: Product = {
  author: 'pjchender',
  publishedAt: '20200831',
};
type Software = {
  platform: string;
  releasedAt: string;
};
type Hardware = {
  RAM: string;
  CPU: string;
};
type MobilePhone = Software & Hardware;
// 要符合 MobilePhone 這個型別的話,Software 和 Hardware 中的任何一個屬性都不能少。
const iphone11: MobilePhone = {
  platform: 'ios',
  releasedAt: '20190919',
  RAM: '4GB',
  CPU: 'A13',
};
Type Alias 和 Interface 基本上是不同的概念,雖然有時可以達到類似的效果。一般來說,若是要在 React 中定義 props 或 state 的型別時,慣例上會使用 Type Alias;當若某個元件是要開發給其他人使用到的套件,則這個元件中的 API 會建議使用 Interface,讓使用此套件的開發者更方便奠基在你提供的方法上再添加其他屬性。
interface Hardware {
  RAM: string;
  CPU: string;
}
interface Software {
  platform: string;
  releasedAt: string;
}
interface MobilePhone extends Software, Hardware {
  price: number;
  brand: string;
}
const iphone11: MobilePhone = {
  price: 24900,
  brand: 'apple',
  platform: 'ios',
  releasedAt: '20190919',
  RAM: '4GB',
  CPU: 'A13',
};
any 是 TypeScript 內建的一個型別,基本上 any 表示的就是「什麼都可以」
有些時候真的無法確定會得到什麼樣的結果,例如 JSON.parse() 這個方法的回傳值就會定義為 any
但在實際的開發過程中,應該要盡可能避免去使用 any
const Link = (props: { content: string }) => {
  const { content } = props;
  return (
    // ...
   )
}