Day07:【TypeScript 学起来】原始资料型别 Primitive Types

Q: 软件工程师最常说的谎言有哪些?
A: //TODO
连假结束 wednesday blue 啥都是 //todo


string (字串)

使用 string 定义字串型别:

const myName: string = 'iris';
const myAge: number = 18;

const sentence: string = `Hello, my name is ${myName}.
I'll be ${myAge + 1} years old next month.`;

number (数值)

使用 number 定义数值型别:

const decLiteral: number = 6;
const notANumber: number = NaN;
const infinityNumber: number = Infinity;

boolean (布林值)

使用 boolean 定义布林值型别:

const isDone: boolean = false;

null & undefined

在 JavaScript 中,null 是已经赋予值, 而值为空值。 undefined 则是宣告了未被赋值。

在 TypeScript 中, 这两个值的运用取决於 tsconfig 中是否设定了严格检查strictNullChecks。而 strictNullChecks 的预设是 false。

但如果打开了"strict": true(预设会打开), 则启用所有严格类型检查选项,包含strictNullChecks。

如何产生及设定 tsconfig 请参考 day05

strictNullChecks off

我们先把 strictNullChecks 设定为 false,这时候可以赋值给其他型别为 null 或 undefined。

null:

const n: null = null;
//如:赋值给string型别
const city: string = n;
console.log("city", city);

undefined:

const u: undefined = undefined;
//如:赋值给number型别
const price: number = u;
console.log("price", price);

strictNullChecks on

这时候我们就可以在档案上看到会报错,Type 'null' is not assignable to type 'string'.
在严格检查下, 是不能赋值给其他型别的。

报错了那怎麽办?

若在严格检查模式下, 达到 false 的效果, 我们就需要用到 Union Types (联合型别),让值可以有多种型别。

const n2: null = null;
const city2: string | null  = n2; //可以是string 或者 null
const city3: string | null  = "taipei"; 

const u2: undefined = undefined;
const price2: number | undefined  = u2; //可以是number 或者 undefined
const price3: number | undefined  = 100; 

耶 Primitive Types 搞定,没想到 null & undefined写那麽多,Union Types (联合型别)後面也会再详细介绍,接下来我们来看看 Object Types 了~


参考资料

https://willh.gitbook.io/typescript-tutorial/basics/primitive-data-types
https://www.typescriptlang.org/docs/handbook/2/everyday-types.html
https://www.typescriptlang.org/zh/tsconfig#strictNullChecks


<<:  【心得】你今天种菜了吗? grid之路-grid的使用(5)

>>:  DNS 服务器之间的区域传输(Zone transfer)

第五章

依照之前介绍的内容都是属於在Hostinger提供的功能面,当然还有许多细项的功能或建置时会用到的,...

【心得】你今天种菜了吗? grid之路-grid的使用(5)

前言 既然可以使用grid-area为每个区域命名,并填入grid-template-areas中,...

Day5 — 前导:使用工具介绍

(因前几天有其他事情要处理因此断赛,不过在可能范围内还是会将内容补齐) 要撰写 AVR 程序码并编译...

【C language part 3】条件&回圈

条件判断 Decision Control Statement 为了应付程序可能遇到的各种状况,C ...

[2020铁人赛] Day29 - 切换身分Impersonation

通常系统中如果要区分windows权限只要在IIS内设定好即可,但有时候可能为了控管windows帐...