本篇文章為基礎(chǔ)數(shù)據(jù)類型的進階,需要對TypeScript的基礎(chǔ)數(shù)據(jù)類型有所了解,不了解的童鞋可先花費兩分鐘看下《第一話:基礎(chǔ)數(shù)據(jù)類型》,好了廢話不多,開始正題。
元組Tuple
三要素:1、數(shù)組? 2、已知元素數(shù)量和類型? 3、各元素的類型可不相同
聲明? let x: [string, number];?
使用(賦值) x = [ 'hello', 123]? // OK? ? ? ? ? ? ?x = [ 123, 'hello' ] // ERROR
訪問越界元素時,會使用聯(lián)合類型替代
x[3] = 'world' // OK? string is (string | number)
x[4] = true // ERROR
any or Object
兩個數(shù)據(jù)類型的變量都允許給它賦任意值
let x: any = 4; x = 'hello'; x = true;
let o: object = 4; o = [ '123 ']; o = false;
但是any類型上可以調(diào)用任意方法,而object不能調(diào)用任意方法
o.toFixed(); // ERROR: toFixed doesn't exist on type 'object'
Null and Undefined
默認情況下null和undefined可以賦值給所有類型
let n: number = null; n = undefined;?
let s: string = null; s = undefined;
當指定了--strictNullChecks時,則null和undefined只能賦值給他們各自和void。
--strictNullChecks配置:不配置默認為false
方法一: tsconfig.json文件 --> compilerOptions --> 'strictNullChecks': true/false
方法二:手動進行文件編譯時
