白話文:幾個例子立刻看懂typescript基礎類型

TS入門:基礎類型less

// 基礎類型
// 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);
相關文章
相關標籤/搜索