Day12: 【TypeScript 学起来】只有 TS 才有的型别: Literal Types(字面值型别) / Tuple (元组)

工程师A: 觉得当工程师好累 想换一行怎麽办
工程师B: 按一下 enter 啊
工程师A:......

很常工程师之间都聊不下去了 更何况是pm 你说是不是....
今天来介绍Literal Types(字面值型别) / Tuple (元组)。


Literal Types 字面值型别

string literal types

就是值的表现方式,某些特殊的"值"可以当作"型别"来使用,用来约束取值只能是某几个字串中的一个。 如下方让 x 变数的字面值为“hello”。

let x: "hello" = "hello";
x = "hello"; //ok
x = "howdy";  //Type '"howdy"' is not assignable to type '"hello"'

但很少情况会使用到一个变数只有一个值,我们可以将想要的值结合起来, 如 alignment 给予3个字面值,其参数要符合其中一个。如果不符合这3个值的其中一个或写错字, 都会报错。

function printText(s: string, alignment: "left" | "right" | "center") {
    console.log(`${s} placed at the ${alignment}`)
}
printText("Hello, world", "left");
printText("G'day, mate", "centre");
//error: Argument of type '"centre"' is not assignable to parameter of type '"left" | "right" | "center"'.


numeric literal types

除了文字上, 数字的操作也一样:
执行compare函式的回传值只能 -1、0 和 1。

function compare(a: string, b: string): -1 | 0 | 1 {
  return a === b ? 0 : a > b ? 1 : -1;
}

non-literal types

非字面值型别也可以结合操作:

interface Options {
  width: number;
}
function configure(x: Options | "auto") {
   console.log(x);
}
configure({ width: 100 });
configure("auto");
configure("automatic"); // 不符Options 及 “auto”
//error: Argument of type '"automatic"' is not assignable to parameter of type 'Options | "auto"'.


Tuple 元组

Tuple 就是合并了不同型别的物件。
定义一对值分别为 string 和 number 的元组:

const iris: [string, number] = ['iris', 18];

可以针对型别有的属性进行使用、赋值。但当直接对元组型别的变数进行初始化或者赋值,需提供所有项目。如果要新增不同型别的项目也是无法的:

let tom: [string, number];
tom = ['tom', 18]; //如果只有宣告tom没赋值,会是undefined,tsconfig strictNullChecks 打开的话会报错提醒
tom[0] = 'Tom'; //ok
tom[1] = 25; //ok
tom[0].slice(1); //ok
tom[1].toFixed(2); //ok
tom.push('male'); //ok

tom = ['tom chen']; //error:Property '1' is missing in type '[string]' but required in type '[string, number]'.
tom.push(true); //error: Argument of type 'true' is not assignable to parameter of type 'string | number'.

边学习边纪录的测试例子,不嫌弃可参考这里

感谢阅读,明天见~~


参考资料

https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#literal-types
https://willh.gitbook.io/typescript-tutorial/advanced/tuple


<<:  Day20-"字串练习-3"

>>:  Day 13 | 魔术方块AR游戏开发Part2 - 魔术方块侦测

ISO 27001 机房管理部份之三

ISO 27001 机房管理部份之三 稽核分三种 : 内部稽核 (例如 : 稽核组长、稽核小组) 外...

成员 7 人:怪异的是,我本来很讨厌你!

你的公司,订好制度了吗? ......还没的话,不要看这篇。 <<< 回头分隔线:...

Day 17 AWS云端实作起手式第七弹 让开机器变得很自动自发Auto Scaling-ReadNode设置

关於Auto Scaling的建置,我们预计会花两到三天的时间来做比较详细说明。 参考Udemy A...

【Day 29】练习专案 2/2 - Figma To Flutter

今日要点 》前言 》介绍 Figma 汇出 Dark code 》程序架构研究 前言 前一天的练习专...

【Day 5_ Arm Mali GPU家族究竟是何方神圣_下篇】

延续上篇还没介绍完的Arm Mali GPU系列解决方案,今天要来接着介绍Mali-G510 GPU...