1.类型声明
var [变量名] : [类型] = 值;
let name:string;
let age:number=12
再vue3中声明ts的ref响应式类型数据
let show:Ref<boolean>=ref(true)
2.基本类型
JavaScript 语言(注意,不是 TypeScript)将值分成 8 种类型。
- boolean
- string
- number
- bigint
- symbol
- object
- undefined
- null
TypeScript 继承了 JavaScript 的类型设计,以上 8 种类型可以看作 TypeScript 的基本类型。
boolean 类型
boolean
类型只包含true
和false
两个布尔值。
const x: boolean = true;
const y: boolean = false;
string 类型
string
类型包含所有字符串。
typescript
const x: string = "hello";
const y: string = `${x} world`;
number 类型
number
类型包含所有整数和浮点数。
typescript
const x: number = 123;
const y: number = 3.14;
const z: number = 0xffff;
数组类型
// 在元素类型后面加上[]
let arr: number[] = [1, 2];
// 或者使用数组泛型
let arr: Array<number> = [1, 2];
元组
let x: [string, number];
x = ['Runoob', 1]; // 运行正常
x = [1, 'Runoob']; // 报错
console.log(x[0]); // 输出 Runoob
枚举
enum Color {Red, Green, Blue};
let c: Color = Color.Blue;
console.log(c); // 输出 2
void
用于标识方法返回值的类型,表示该方法没有返回值。
function hello(): void {
alert("Hello Runoob");
}
Any 类型
任意值是 TypeScript 针对编程时类型不明确的变量使用的一种数据类型,
Null 和 Undefined
null
在 JavaScript 中 null 表示 "什么都没有"。
null是一个只有一个值的特殊类型。表示一个空对象引用。
用 typeof 检测 null 返回是 object。
undefined
在 JavaScript 中, undefined 是一个没有设置值的变量。
typeof 一个没有值的变量会返回 undefined。
Null 和 Undefined 是其他任何类型(包括 void)的子类型,可以赋值给其它类型,如数字类型,此时,赋值后的类型会变成 null 或 undefined。而在TypeScript中启用严格的空校验(--strictNullChecks)特性,就可以使得null 和 undefined 只能被赋值给 void 或本身对应的类型,示例代码如下:
// 启用 --strictNullChecks let x: number; x = 1; // 编译正确 x = undefined; // 编译错误 x = null; // 编译错误