TS入門:基礎型別
// 基礎型別
// Number
let num: number = 321321;
// String
let str: string = `hello world ${num}`;
// Array
let arr: number[] = [1, 2, 3];
let arr1: Array<string> = [`1`, `2`, `3`];
// Tuple 元組
let tuple: [string, number, boolean];
tuple = [`id`, 1001, true];
// enum 列舉
enum Days { Sun = 7, Mon = 1, Tue, Wed, Thu, Fri, Sat };
let day: Days = Days.Sun;
console.log(Days[`Wed`] === 3); // true
console.log(day); // 7
// Any
let notSure: any = `string`;
notSure = 123;
let notSureArr: any[] = [`1321`, 123, true];
// Void
let useless: void = undefined;
useless = null; // 只能賦值null or undefined
function fun(num: number): void {
console.log(num + `%`); // 無返回值應當定義為void
}
// Null & Undefined
let n: null = null;
let u: undefined = undefined;
num = u; //可賦值給其他任何其他型別
console.log(num); // undefined
// Never 表示永遠不存在的值的型別
function infinite(): never {
while (true) {
}
}
// 型別斷言,告訴ts對型別非常肯定並經過了檢查
let userInput: any = `hello there`; // 此處假設我可以非常確定是字串
let strLength: number = (<string>userInput).length; // 斷言userInput一定是字串
console.log(<number>strLength === 11); // true 斷言strLength一定是數字
let obj: object = {
userInput: userInput as string, // 也可使用as語法
strLength: strLength as number,
};
console.log(obj);