提示:TypeScript中的基本类型
TypeScript
(计算机编程语言)简称:TS,是JavaScript 的超集
。简单来说就是:JS 有的 TS 都有。JS写的代码在TS的环境下都能跑;对了,TS是微软
设计并发布的。
类型声明是TS非常重要的一个特点;
通过类型声明可以指定TS中变量(参数、形参)的类型;
指定类型后,当为变量赋值时,TS编译器会自动检查值是否符合类型声明,符合则赋值,否则报错;
简而言之,类型声明给变量设置了类型,使得变量只能存储某种类型的值;
let 变量: 类型;
let 变量: 类型 = 值;
function fn(参数: 类型, 参数: 类型): 类型{
...
}
类型 | 例子 | 描述 |
---|---|---|
number | 1, -33, 2.5 | 任意数字 |
string | ‘hi’, “hi”, hi | 任意字符串 |
boolean | true、false | 布尔值true或false |
字面量 | 其本身 | 限制变量的值就是该字面量的值 |
any | * | 任意类型 |
unknown | * | 类型安全的any |
void | 空值(undefined) | 没有值(或undefined) |
never | 没有值 | 不能是任何值 |
object | {name:‘孙悟空’} | 任意的JS对象 |
array | [1,2,3] | 任意JS数组 |
tuple | [4,5] | 元组,TS新增类型,固定长度数组 |
enum | enum{A, B} | 枚举,TS中新增类型 |
let decimal: number = 6;
let hex: number = 0xf00d;
let binary: number = 0b1010;
let octal: number = 0o744;
let big: bigint = 100n;
let isDone: boolean = false;
let color: string = "blue";
color = 'red';
let fullName: string = `Bob Bobbington`;
let age: number = 37;
let sentence: string = `Hello, my name is ${fullName}.
I'll be ${age + 1} years old next month.`;
let color: 'red' | 'blue' | 'black';
let num: 1 | 2 | 3 | 4 | 5;
let d: any = 4;
d = 'hello';
d = true;
let notSure: unknown = 4;
notSure = 'hello';
let unusable: void = undefined;
function error(message: string): never {
throw new Error(message);
}
let obj: object = {};
let list: number[] = [1, 2, 3];
let list: Array<number> = [1, 2, 3];
let x: [string, number];
x = ["hello", 10];
enum Color {
Red,
Green,
Blue,
}
let c: Color = Color.Green;
enum Color {
Red = 1,
Green,
Blue,
}
let c: Color = Color.Green;
enum Color {
Red = 1,
Green = 2,
Blue = 4,
}
let c: Color = Color.Green;
第一种
let someValue: unknown = "this is a string";
let strLength: number = (someValue as string).length;
第二种
let someValue: unknown = "this is a string";
let strLength: number = (<string>someValue).length;