iT邦幫忙

2021 iThome 鐵人賽

DAY 2
0
自我挑戰組

TypeScript 能手養成之旅系列 第 11

TypeScript 能手養成之旅 Day 11 明文型別(Literal Types)

前言

明文型別(Literal Types),一開始看到這個名詞,真的不是很好懂,不過實際去了解後,你會有原來的感覺。

簡單來說明文型別(Literal Types)就是明著說只有哪些值可以使用,以明確的賦值來約束。

字串明文型別

let cy: 'omg';
cy = 'omg' // pass
cy = 'wrong' // Type '"wrong"' is not assignable to type '"omg"'.

試著建立一個 cy 變數,並使用字串明文型別 omg。接下來試著去賦值,發現如果是 omg 是沒問題的,但其他的將會噴錯。

cy = null
cy = undefined

進一步嘗試將 null 和 undefined 賦值給 cy,在 strictNullChecks 預設情況下,是不會噴錯的,但如果將設定開啟,將會被嚴格檢視,就會噴錯。

型別別名(Type Alias)

應用 字串明文型別 並中間穿插介紹一下 型別別名,就字面上的意思,就是替型別來取別名,而使用 type 來進行宣告,如下:

type Size = 'small' | 'middle' | 'large'
function putImages(width: number, screen: Size) {
  // ...
}

putImages(100, 'middle') // pass
putImages(100, 'xxl') // wrong

通常我們用來簡化程式碼,或者是用更好的命名使更好理解此型別。

數字明文型別(Numeric Literal Types)

和字串一樣,可以使用 數字明文型 來限定變數只能是哪些數字。

let validNumber: 1 | 11 | 111;
validNumber = 1;  // pass
validNumber = 22; // Type '22' is not assignable to type '1 | 11 | 111'.
validNumber = 11; // pass

布林明文型別(Boolean Literal Types)

來到這,相信大家都知道怎麼做了,我們就直接來使用 布林明文型別

let isTrue: true
let isFalse: false

isTrue = false // Type 'false' is not assignable to type 'true'.
isTrue = 'not true' // Type '"not true"' is not assignable to type 'true'.
isFalse = true // Type 'true' is not assignable to type 'false'.
isFalse = false // pass

列舉明文型別(Enum Literal Types)

我們來使用函式來實際應用 列舉明文型別

const enum Campus {
  Language = 'Ruby',
  month = 3
}

function learnSkill(campus: Campus.Language): 'Ruby' {
  return 'Ruby'
}

function learnTime(campus: Campus.month): 3 {
  return 3
};

function campusDetail(campus: Campus): 'Ruby' | 3 {
  switch (campus) {
    case Campus.Language:
      return 'Ruby';
    case Campus.month:
      return 3;
  }
}

const skill =  learnSkill(Campus.Language)
console.log(skill) // Ruby
const time = learnTime(Campus.month)
console.log(time) // 3
const languageDetail = campusDetail(Campus.Language)
console.log(languageDetail) // Ruby
const monthDetail = campusDetail(Campus.month)
console.log(monthDetail) // 3

結語

今天初步介紹了 明文型別 和其運用,以及中間還有型別別名(Type Alias) 的小插曲,明天我們將繼續努力,加油~


上一篇
TypeScript 能手養成之旅 Day 10 物件型別-擴充型別-列舉(Enum)
下一篇
TypeScript 能手養成之旅 Day 12 泛用型別(Generics Types)
系列文
TypeScript 能手養成之旅16
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言