TypeScript教程
ts数据类型
说明:ts中数据类型包括js已有的数据类型、ts新增的数据类型,本文讲解ts新增的数据类型。
-
any
-
unknown
-
never
-
void
-
tuple
-
enum
-
type
一、any
说明:任意类型(相当于关闭类型检查)
1.显式any
let any1: any
console.log("any1 type:", typeof any1) //any1 type: undefined
any1 = 1
console.log("any1 type:", typeof any1) //any1 type: number
any1 = true
console.log("any1 type:", typeof any1) //any1 type: boolean
any1 = "a"
console.log("any1 type:", typeof any1) //any1 type: string
let str_any1: string
str_any1 = any1;
console.log("any1/2 value:", any1 / 2)
//any1=1 any1/2 value:0.5; any1:true any1/2 value:0.5; any1:"a" any1/2 value: NaN;
2.隐式any
let any2
console.log("any2 type:", typeof any2) //any2 type: undefined
any2 = 1
console.log("any2 type:", typeof any2) //any2 type: number
any2 = true
console.log("any2 type:", typeof any2) //any2 type: boolean
any2 = "a"
console.log("any2 type:", typeof any2) //any2 type: string
备注:未声明变量类型且未设置默认值
二、unknown
说明:未知类型(相当于类型安全的any)
let unknown1: unknown
console.log("unknown1 type:", typeof unknown1) //unknown1 type: undefined
unknown1 = 1
console.log("unknown1 type:", typeof unknown1) //unknown1 type: number
unknown1 = true
console.log("unknown1 type:", typeof unknown1) //unknown1 type: boolean
unknown1 = "a"
console.log("unknown1 type:", typeof unknown1) //unknown1 type: string
let str_unknown1: string
//str_unknown1=unknown1; //TS2322: Type unknown is not assignable to type string
if (typeof unknown1 === 'string') {
str_unknown1 = unknown1;
}
str_unknown1 = unknown1 as string
str_unknown1 = <string> unknown1
//console.log("unknown1/2 value:",unknown1/2) //TS18046: unknown1 is of type unknown
if (typeof unknown1 === 'number') {
console.log("unknown1/2 value:", unknown1 as number / 2)
}
console.log("unknown1/2 value:", unknown1 as number / 2)
console.log("unknown1/2 value:", <number> unknown1 / 2)
//unknown1=1 unknown1/2 value:0.5; unknown1:true unknown1/2 value:0.5; unknown1:"a" unknown1/2 value: NaN;
备注:
any任意类型,相当于关闭类型检查;unknown未知类型,仍然会进行类型检查。
三、never
说明:不存在值所属的类型(0,false,'',undefined,null等任何类型都不能赋值给never)
let never1: never
//never1=undefined; //TS2322: Type undefined is not assignable to type never
//never1=null; //TS2322: Type null is not assignable to type never
function throwError(message: string): never {
throw new Error(message);
}
function handleStatus(status: 1 | 2 | 3) {
switch (status) {
case 1:
console.log('状态1');
break;
case 2:
console.log('状态2');
break;
//case 3:
//console.log('状态3');
//break;
default:
//前置类型检查是否已涵盖全部状态
const check: never = status; //TS2322: Type number is not assignable to type never
throw new Error(`异常状态: ${status}`);
}
}
四、void
说明:没有任何类型值的特殊类型
let void1: void
//void1=null; //TS2322: Type null is not assignable to type void
void1 = undefined;
//应用举例
function sayHello(): void {
console.log("Hello, world!");
//return; //可选
//return undefined; //可选
//return "Hello"; //TS2322: Type string is not assignable to type void
}
let void_result = sayHello();
//if(void_result){ //TS1345: An expression of type void cannot be tested for truthiness.
//console.log(void_result)
//}
备注:如果一个函数没有显式地指定返回类型,且没有return或return没有指定返回,那么该函数的返回类型会被隐式地推断为undefined。
五、tuple
说明:一种特殊类型数组,其中元素具有多类型、有序性的特点,存储一定数量的元素。
let tuple1: [string, number, boolean]
tuple1 = ["a", 1, true]
tuple1[2] = false
//可选参数
let tuple2: [string, number, boolean?]
tuple2 = ["a", 1]
tuple2 = ["a", 1, true]
//剩余参数
let tuple3: [string, number, ...boolean[]]
tuple3 = ["a", 1, true, false]
六、enum
说明:用于定义一组命名的常量值,提高代码的可读性和可维护性。
1.常量枚举
①数字枚举(有反向映射)
enum Direction1 {
Up,
Down,
Left,
Right
}
console.log("Direction1 value:", Direction1)
//{
//"0": "Up",
//"1": "Down",
//"2": "Left",
//"3": "Right",
//"Up": 0,
//"Down": 1,
//"Left": 2,
//"Right": 3
//}
console.log("Direction1.Up value:", Direction1.Up) //0
console.log("Direction1[0] value:", Direction1[0]) //Up
enum Direction2 {
Up = 5,
Down,
Left,
Right
}
console.log("Direction2 value:", Direction2)
//{
//"5": "Up",
//"6": "Down",
//"7": "Left",
//"8": "Right",
//"Up": 5,
//"Down": 6,
//"Left": 7,
//"Right": 8
//}
console.log("Direction2.Up value:", Direction2.Up) //5
console.log("Direction2[5] value:", Direction2[5]) //Up
console.log("Direction2.Down value:", Direction2.Down) //6
备注:成员值依次递增,默认从0开始,可以指定初始值。
②字符串枚举(无反向映射)
enum Direction3 {
Up = "up",
Down = "down",
Left = "left",
Right = "right"
}
console.log("Direction3 value:", Direction3)
//{
//"Up": "up",
//"Down": "down",
//"Left": "left",
//"Right": "right"
//}
console.log("Direction3.Up value:", Direction3.Up) //up
console.log("Direction3.Up==up result:", Direction3.Up == "up") //true
2.计算成员
//计算成员
enum Direction4 {
A = "A".charCodeAt(0),
B = "B".charCodeAt(0)
}
console.log("Direction4 value:", Direction4)
//{
//"65": "A",
//"66": "B",
//"A": 65,
//"B": 66
//}
3.常量枚举(减少编译后代码量 无法使用计算成员)
①不使用常量枚举编译前后
//编译前
enum Direction5 {
Up,
Down,
Left,
Right
}
const direction1 = Direction5.Up
//编译后
var Direction5;
(function (Direction5) {
Direction5[Direction5["Up"] = 0] = "Up";
Direction5[Direction5["Down"] = 1] = "Down";
Direction5[Direction5["Left"] = 2] = "Left";
Direction5[Direction5["Right"] = 3] = "Right";
})(Direction5 || (Direction5 = {}));
const direction1 = Direction5.Up;
②使用了常量枚举编译前后
//编译前
const enum Direction6 {
Up,
Down,
Left,
Right
}
const direction2 = Direction6.Up
//编译后
const direction2 = 0 /* Direction6.Up */;
七、type
1.类型别名
type User = {
name: string,
age: number
}
let user1: User = {
name: "张三",
age: 20
}
type customFunction = () => void
const customFunction1: customFunction = () => "test";
备注:使用类型进行函数类型限制时,返回值为void时,并未严格按照返回值为void限制。
2.联合类型
type StringOrNumber = string | number
let stringOrNumber1:StringOrNumber = "YES"
type Gender = '男' | '女'
let gender1:Gender = '男'
3.交叉类型
type School = {
schoolName: string
}
type Grade = {
gradeName: string
}
type Class = {
className: string
}
type Student = School & Grade & Class
let student1: Student = {
schoolName: "学校",
gradeName: "年级",
className: "班级"
}
八、类型声明文件
说明:用于为已有的JavaScript库或模块提供类型信息,使TypeScript编译器在使用时进行类型检查(以.d.ts为后缀)。
1.test.js
export function sum(a, b) {
return a + b;
}
2.test.d.ts
declare function sum(a: number, b: number): number;
export {sum};
3.index.ts
import {sum} from "./test.js";
//const totalSum = sum("a", 2); //TS2345: Argument of type string is not assignable to parameter of type number
const totalSum = sum(1, 2); //totalSum 类型为 number
文章首发公众号自学Java教程 欢迎关注解锁更多精彩内容!