交叉类型 &
如果我们需要把两个不同的对象合并为一个对象,则该对象为这两个对象的交叉类型
# T & U
const mergeFunc = <T, U>(obj1: T, obj2: U) :T & U => {
return Object.assign(obj1, obj2) as T & U;
}
联合类型 |
如果我们需要一个函数接收number或者string类型,返回值为参数的长度,那么这个方法的参数就需要用联合类型来描述
// string | number
const getLengthFunc = (content: string | number) : number => {
if(typeof content === "string") return content.length;
else {
return content.toString().length;
}
}
字面量类型
字面量类型中包括字符串字面量、数字字面量
字符串字面量
type str = "hello"
const name: str = "hello";
// 一旦指定了name的类型为str,那么它(name)只能用 'hello'作为变量name的值
type Direction = 'north' | 'west' | 'south' | 'east'

例:字符串字面量
数字字面量
type Age = 18;
interface Person {
name: String,
age: Age
}
const p1 : Person = {
name: "any string",
age: 18 // 这块只能写18
}

例:数字字面量
可辨识联合
两要素
1.具有普通的单例类型属性(作为辨识特征)
2.一个类型别名包含了哪些类型的联合
interface Square {
kind: 'square',
size: number
}
interface Rectangle {
kind: 'rectangle',
width: number,
height: number
}
interface Circle {
kind: 'circle',
radius: number
}
type Shape = Square | Rectangle | Circle
const getShapeArea = (s: Shape): number => {
switch(s.kind) {
case 'circle': return Math.PI * s.radius * s.radius;
case 'rectangle': return s.width * s.height / 2;
case 'square': return s.size * s.size;
}
}

例:可辨识联合
索引类型
1.索引类型查询 keyof
interface info {
name: string,
age: number
}
let infoprop: keyof info;
// 那么infoprop就只能定义为 info接口下定义的字段
infoprop = 'name'; // ok
infoprop = 'age'; // ok
infoprop = 'gender'; // error

例:索引类型
2.索引访问操作符[]
通过 [] 索引类型访问操作符, 我们就能得到某个索引的类型

索引类型访问操作符.jpg
类型如果为null、undefined、never,则不会被访问到
interface Type {
a: string;
b: never;
c: boolean;
d: number;
e: object;
f: null;
g: undefined
}
type Test = Type[keyof Type];
let prop: Test =
