欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

typescript学习-基础类型

程序员文章站 2022-07-03 21:57:19
...
/**
 * 布尔值
 */
let isDone: boolean = false;

/**
 * 数字
*/
let decLiteral: number = 6;
let hexLiteral: number = 0xf00d;

/**
 * 字符串
*/
let userName: string = `smith`;

/**
 * 数组
*/
let list: number[] = [1, 2, 3];
let list2: Array<number> = [1, 2, 3];

/**
 * 元组
*/
let x: [string, number];
x = ['hello', 10];
x[2] = 'world';
// console.log(x);

/**
 * 枚举
*/
enum Color { Red = 1, Green, Blue };
let colorName: string = Color[1];
// console.log(colorName);

/**
 * Any
*/
let notSure: any = 4;
notSure = 'maybe a string instead';
notSure = false;
// console.log(notSure);
// notSure.ifItExists();
// notSure.toFixed();

let lists: any[] = [1, true, 'free'];
lists[1] = 100;
// console.log(lists);

/**
 * Void
*/
function warnUser(): void {
    alert('This is my warning message');
}
// warnUser();
let unusable: void = undefined;
let unusable2: void = null;


/**
 * Never
*/

function error (message:string):never{
    throw new Error(message);
}

function fail(){
    return error('something failed');
}

function infiniteLoop():never{
    while(true){
    }
}
// console.log(fail())

/**
 * 类型断言
*/ 

let someValue:any='this is a string';

let strLength:number=(<string>someValue).length;
let strLength2:number=(someValue as string).length;