1-typescript基本数据类型

2023-05-04  本文已影响0人  Angrybird233
  1. 数字 number
let age: number = 24;
let double_age: number = 48;
  1. 字符串 string
let words: string = "what's is your question?";
let sport_name: string = 'football';
const name:string =  '张三';
const sentence: string = `my name is ${ name }, my favorite sport is ${ sport_name }`;
  1. 布尔值 boolean
let is_right: boolean = true;
  1. 数组 Array
方式一:

let user_list: string[] = ['张三', '李四', '老六'];
let temperatures: number[] = [12, 15, 24, 25];

方式二:
let user_list: Array<string> = ['张三', '李四', '老六'];
let temperatures: Array<number> = [12, 15, 24, 25];

  1. 元祖 Tuple
let x: [string, number] = ['hello', 100];  // OK
let y: [string, number] = [12, 'world'] // Error (incorrectly)
x[3] = '张三'  //ok 字符串可以赋值给(string | number)类型
x[6] = true; // Error, 布尔不是(string | number)类型
console.log(x[0].substr(1)); // OK
console.log(x[1].substr(1)); // Error, 'number' does not have 'substr'
console.log(x[5].toString())  // OK, 'string' 和 'number' 都有 toString
  1. 枚举 enum
enum Color {Red = 1, Green = 2, Blue = 4}
let c: Color = Color.Green;

let colorName: string = Color[2];
console.log(colorName);  // 显示'Green'因为上面代码里它的值是2
  1. Any
let not_sure: any =  6;
not_sure = 'i'm not sure what is it '
not_sure = false

not_sure = 100.666665
not_sure.toFixed(2) // OK   toFixed exists (but the compiler doesn't check)

let prettySure: Object = 4;
prettySure.toFixed(); // Error: Property 'toFixed' doesn't exist on type 'Object'

let list: any[] = [1, true, "free"];
list[1] = 100;
  1. void
function sayHello(): void {
  console.log(" hellow world")
}

let unusable: void = undefined;
  1. null 和undefind
let u: undefined = undefined;
let n: null = null;
  1. never
// 返回never的函数必须存在无法达到的终点
function error(message: string): never {
    throw new Error(message);
}

// 推断的返回值类型为never
function fail() {
    return error("Something failed");
}

// 返回never的函数必须存在无法达到的终点
function infiniteLoop(): never {
    while (true) {
    }
}
  1. object
declare function create(o: object | null): void;
  1. 类型断言
let someValue: any = "this is a string";
let strLength: number = (<string>someValue).length;  // 将someValue断言为string后取string的length

let someValue: any = "this is a string";
let strLength: number = (someValue as string).length  //  将someValue断言为string后取string的length
上一篇 下一篇

猜你喜欢

热点阅读