数据类型
函数返回值
/**
* 函数返回值 箭头函数写法
* @param a 数值类型
* @param b 可选参数
* @param c 带默认值的参数
* @returns
*/
let demo = (a: number, b: number = 2, c?:number):string => {
return `a + b + c = ${a + b + (c || 0)}`
}
console.log(demo(1, 2))
布尔类型
const isDone: boolean = true;
数值类型
const demo1: number = 6
const demo2: number = 3.33
字符串
let nickname: string = "ricky";
let sentence: string = `Hello, my name is ${ nickname }`
数组
let list: number[] = [1, 2, 3];
let list2: Array<number> = [1, 2, 3];
元组
let x: [string, number];
x = ['hello', 10]; // OK
x = ['hello', 10, false]; // Error
x = [10, 'hello']; // Error
Union联合
允许我们在变量或函数参数中使用多种数据类型,这被称为联合类型
let code: (string | number);
code = 123; // OK
code = "ABC"; // OK
// code = false; // 编译错误
console.log(code)
function demo(code: (string | number))
{
console.log(code)
}
demo(123)
demo('hello world')
// demo(false) // 编译错误
unknown
unknown在ts3.0加入,用法同any,表示当前并不知道该变量为哪种类型,不过不会关闭类型检查,在unknown类型被确定为某一中类型之前,不能进行实例化,getter,函数执行等
let demo: unknown = 4;
demo = "hello world"; // OK
demo.toString(); // ERROR
Void
void用于表示没有数据,因为只能为void变量赋undefined和null
let demo: void = undefined;
function hello(): void
{
console.log('hello world');
}
Any
let demo: any = 4;
demo = "hello world"; // OK
demo.toString(); // OK