// 不多说,上代码
// main.ts -> 编译tsc main.ts -> 运行node main.js
(()=>{
// 基础类型:... 不许用其他类型数据改变当前变量类型
// 布尔值,数字,字符串,undefined 和 null
let num1:number = 1
let str1:string = "3"
console.log(num1);
console.log(str1);
console.log(num1+str1); // 13
// 数组
let list1: number[] = [1, 2, 3]
// 泛型写法
let list2: Array<number> = [3, 2, 1]
console.log(list1);
console.log(list2);
//元组 Tuple
console.log('元组');
let t1: [string, number]
t1 = ['hello', 10] // OK
console.log(t1);
console.log(t1[0].split('e'));// 指定字符分割为字符数组
console.log(t1[1].toFixed(2));// 保留两位小数
// t1 = [10, 'hello'] // Error
// 枚举
enum Color {
Red,
Green,
Blue
}
// 枚举数值默认从0开始依次递增
// 根据特定的名称得到对应的枚举数值
let myColor: Color = Color.Green // 1
console.log(myColor, Color.Red, Color.Blue) // 1 0 2
enum Color2 { Red = 1, Green, Blue }
let c: Color2 = Color2.Green
console.log(c); // 2
enum Color3 { Red = 1, Green, Blue }
let colorName: string = Color3[3]
console.log(colorName) // 'Blue'
// any在编程阶段还不清楚类型的变量指定一个类型。 这些值可能来自于动态的内容,比如来自用户输入或第三方代码库。
let list: any[] = [1, true, 'free']
list[1] = 100
list[2] = true
console.log(list); // (3) [1, 100, true]
let notSure: any = 4
notSure = 'maybe a string'
console.log(notSure);
notSure = false // 也可以是个 boolean
console.log(notSure);
//void 声明一个 void 类型的变量没有什么大用,因为你只能为它赋予 undefined :
let unusable1: void = undefined
// let unusable2: void = null
function fn(): void { // 函数后加:void代表无返回值,可以返回return undefined
console.log('fn()')
// return undefined
// return null // error
// return 1 // error
}
// object object 表示非原始类型,也就是除 number,string,boolean之外的类型。
// 使用 object 类型,就可以更好的表示像 Object.create 这样的 API。
function fn2(obj: object): object {
console.log('fn2()', obj)
return {id: 1}
// return undefined
// return null
}
console.log(fn2(new String('abc')))// {id:1}
// console.log(fn2('abc') // error
console.log(fn2(String))// {id:1}
// 联合类型(Union Types)表示取值可以为多种类型中的一种
// 需求1: 定义一个一个函数得到一个数字或字符串值的字符串形式值
function toString2(x: number | string): string {
return x.toString()
}
// 需求2: 定义一个一个函数得到一个数字或字符串值的长度
function getLength(x: number | string) {
// return x.length // error
// if (x.length) { // error
// return x.length
// } else {
return x.toString().length
// }
}
console.log(toString2(12));
console.log(getLength('333'));
// 类型断言:好比其它语言里的类型转换,但是不进行特殊的数据检查和解构。 它没有运行时的影响,只是在编译阶段起作用。 TypeScript 会假设你,程序员,已经进行了必须的检查。
// 两种形式。 其一是“尖括号”语法, 另一个为 as 语法
/*
方式一: <类型>值
方式二: 值 as 类型 tsx中只能用这种方式
*/
/* 需求: 定义一个函数得到一个字符串或者数值数据的长度 */
function getLength2(x: number | string) {
if ((<string>x).length) {
return (x as string).length
} else {
return x.toString().length
}
}
console.log(getLength2('abcd'), getLength2(1234))// 4 4
// 类型推断: TS会在没有明确的指定类型的时候推测出一个类型
// 有下面2种情况:
// 1. 定义变量时赋值了, 推断为对应的类型.
// 2. 定义变量时没有赋值, 推断为any类型.
/* 定义变量时赋值了, 推断为对应的类型 */
let b9 = 123 // number
// b9 = 'abc' // error
/* 定义变量时没有赋值, 推断为any类型 */
let b10 // any类型
b10 = 123
b10 = 'abc'
})()
TS - typescript 基础数据类型
最新推荐文章于 2024-08-21 16:40:05 发布