TypeScript 复杂数据类型
- 类型推导
在给变量赋值初始值时,会默认将初始值的类型作为该变量的类型,再给该变量赋值其他类型的值时就会报错
let b2 = 1;
// b2 = true; //报错
b2 = 3; //ok
- 联合类型
可以规定为多种类型中的其中一种,个人理解为或。
//联合类型
let b3: number | string;
console.log(b3!.toString()); // 在未确定其类型时 只可用公共方法
b3 = 1;
console.log(b3.toFixed(2)); // 确定类型时 用当前类型的方法
b3 = 'zs';
console.log(b3.toUpperCase()); // 确定类型时 用当前类型的方法
- 类型断言
自信的告诉程序一定会是哪种类型
//类型断言
//告诉程序一定会这样
let b4: number | string;
console.log((b4 as number).toFixed(2)); // 断言告诉程序一定会是number类型
console.log((b4 as string).toUpperCase()); // 断言告诉程序一定会是string类型
console.log((b4 as any as boolean).valueOf()); // 或者使用双重断言来使用其他类型的方法
- 非空断言操作符
只有明确某个值不可能是null
或undefined
时才使用!
function liveDangerously(x?: number | null) {
// No error
console.log(x!.toFixed());
}
- 字面量类型
个人理解为固定值的类型
// 字面量类型 固定的字面量作为类型
// 可以实现枚举效果
let data: 'zs' = 'zs'; //赋值非 'zs' 就会报错
type Move = 'up' | 'down' | 'left' | 'right';
function move(params: Move) {
}
move('up'); // ok
// move('up1'); // 报错
- 类型别名
个人理解为 规定某个对象内只能有哪些类型的key和对应的类型
// 类型别名
type Person = {
name: string,
age: number,
}
let p1: Person = {
// 声明的对象如果属性少于或多于或类型不符和定义的类型字面量 则都会报错
name: 'zs',
age: 30,
}
type ID = string | number;
const id: ID;
注意: 别名是唯一的别名,你不能使用类型别名创建同一个类型的不同版本。 当你使用类型别名的时候,它就跟你编写的类型是一样的。 换句话说,代码看起来可能不合法,但对 TypeScript 依然是合法的,因为两个类型都是同一个类型的别名
- 接口(Interfaces)
接口声明是命名对象类型的另一种方式:
interface Person {
name: string;
age: number;
}
const xiaoWang:Person = {
name: '小王',
age: '19',
}
类型别名与接口的不同
类型别名和接口非常相似,大部分时候可以任意使用,接口几乎所有特性都可以在type
使用,两者最关键的差别在于类型别名本身无法添加新的属性,但是接口可以扩展。
function getBear(){
return {
name: '熊',
honey: true,
}
}
function getBike(){
return {
name: '自行车',
noOil: true,
}
}
// 接口 通过继承扩展类型
interface Animal {
name: string;
}
interface Bear extends Animal {
honey: boolean;
}
const bear: Bear = getBear();
bear.name;
bear.honey;
// Type 通过交集扩展类型
type Car = {
name: string;
}
type Bike = Car & {
noOil: boolean
}
const bike: Bike = getBike()
bike.name;
bike.noOil;
// Interface
// 对一个已经存在的接口添加新的字段
interface Window {
title: string
}
interface Window {
ts: TypeScriptAPI
}
const src = 'const a = "Hello World"';
window.ts.transpileModule(src, {});
// Type
// 创建后不能被改变
type Window = {
title: string
}
type Window = {
ts: TypeScriptAPI
}
// Error: Duplicate identifier 'Window'.