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) 的小插曲,明天我们将继续努力,加油~


<<:  【Day14】数据展示元件 - Card

>>:  Day12 Functional Component的state - useState

Java 关於发送 Https 请求 (HttpsURLConnection 和 HttpURLConnection)

https 协议对於开发者而言其实只是多了一步证书验证的过程,这个证书正常情况下被 jdk/jre/...

CRC-8-CCITT

CRC-8-CCITT SMBus PEC /* https://en.wikipedia.org/...

纯 CSS 毛玻璃特效 - backdrop-filter 属性介绍

几年前的 iOS、MacOS 更新以後,毛玻璃视觉效果越来越受到许多人喜爱,在使用毛玻璃以前,背景与...

新新新手阅读 Angular 文件 - Day07

学习目标 本文章将会是阅读官方文件Add navigation with routing 内容所做的...

[面试][後端]请简述 Node.js 的 Event Loop

熟悉的起手式:「我方便问你一个 Node.js 核心的问题吗?」 这是一个在了解後,无论面试还是工...